biladina biladina - 1 year ago 135
PHP Question

Yii2 Dependent Dropdown Data Not Show

I am using krajee yii2 depdrop in my form. I follow the instruction and my data still not show on depdrop.

This is my _form.php code :

<?php echo $form->field($model, 'id_trayek')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Trayek::find()->all(), 'id_trayek', 'nama_trayek'),
'language' => 'en',
'theme' => Select2::THEME_KRAJEE,
'options' => ['id' => 'id_trayek', 'placeholder' => '-- Pilih Trayek --', 'class' => 'form-control'],
]); ?>

<?php
echo $form->field($model, 'no_bus')->widget(DepDrop::classname(), [
'type'=>DepDrop::TYPE_SELECT2,
'options' => ['id'=>'no_bus', 'class'=>'form-control'],
'pluginOptions'=>[
'depends'=>['id_trayek'],
'placeholder' => '-- Pilih Bus --',
'url' => Url::to(['/surat-jalan/bus'])
]
]);
?>


This is my controller for depdrop url :

public function actionBus() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$id_trayek = end($_POST['depdrop_parents']);
$jenis_bus = Trayek::find()->select('jenis_bus')->andWhere(['id_trayek'=>$id_trayek]);
$list = Bus::find()->andWhere(['jenis_bus'=>$jenis_bus])->asArray()->all();
$selected = null;
if ($id_trayek != null && count($list) > 0) {
$selected = '';
foreach ($list as $i => $bus) {
$out[] = ['no_bus' => $bus['no_bus'], 'no_bus' => $bus['no_bus']];
}

echo Json::encode(['output' => $out, 'selected'=>$selected]);
return;
}
}
echo Json::encode(['output' => '', 'selected'=>'']);
}


in console, I found JSON response is OK and error : TypeError: id is undefined on file dependendent-dropdown.js (line 39, col 49)

Error from console
Error from console

Answer Source

This line is not correct:

$out[] = ['no_bus' => $bus['no_bus'], 'no_bus' => $bus['no_bus']];

Dependent dropdown requires the first array element to be id and the second one to be name. Change to this:

$out[] = ['id' => $bus['no_bus'], 'name' => $bus['no_bus']];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download