Reputation: 1
I have use Extension from Kartik, for create dependent dropdown, called DepDrop.
My dependent schema Regencies->District->Villages
When Create Action, everything Okay, running wells, but when Update Action, in Child Dropdown don't show Selected value.
Here my View Code :
<?= $form->field($model, 'fk_regencies_id')->dropDownList(ArrayHelper::map(Regencies::find()->all(),'id','name'), ['id'=>'regency_id']);?>
<?= Html::hiddenInput($model->fk_districs_id, $model->fk_districs_id, ['id'=>$model->fk_districs_id]) ?>
<?= $form->field($model, 'fk_districs_id')->widget(DepDrop::classname(), [
'options'=>['id'=>'district-id'],
'pluginOptions'=>[
'depends'=>['regency_id'],
'placeholder'=>'Select...',
'url'=>Url::to(['/calonpegawai/district']),
'params'=>[$model->fk_districs_id]
]
]) ?>
And Here My Controller :
public function actionDistrict() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$regency_id = $parents[0];
$param1 = null;
if (!empty($_POST['depdrop_params'])) {
$params = $_POST['depdrop_params'];
$param1 = $params[0]; // get the value of input-type-1
}
$out = Districts::getDistrictList($regency_id);
//$out[1] = ['id'=>$regency_id, 'name'=>$param1];
$selected = Districts::getDefaultDistrict($param1);
//$selected[1] = ['id'=>$regency_id, 'name'=>$param1];
// the getDefaultSubCat function will query the database
// and return the default sub cat for the cat_id
echo Json::encode(['output'=>$out, 'selected'=>$selected]);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}
My Model :
public function getDistrictList($regency_id)
{
$data=\backend\models\Districts::find()
->where(['regency_id'=>$regency_id])
->select(['id','name' ])->asArray()->all();
return $data;
}
public function getDefaultDistrict($param1)
{
$data=\backend\models\Districts::find()
->where(['id'=>$param1])
->select(['id','name' ])->asArray()->all();
return $data;
}
Upvotes: 0
Views: 2615
Reputation: 11
Add in your view:'data'=>[$key=>$value];
<?= $form->field($model, 'fk_regencies_id')->dropDownList(ArrayHelper::map(Regencies::find()->all(),'id','name'), ['id'=>'regency_id']);?>
<?= Html::hiddenInput($model->fk_districs_id, $model->fk_districs_id, ['id'=>$model->fk_districs_id]) ?>
<?= $form->field($model, 'fk_districs_id')->widget(DepDrop::classname(), [
'data' => [$model->fk_regencies_id=>$model->fk_regencies_id],
'options'=>['id'=>'district-id'],
'pluginOptions'=>[
'depends'=>['regency_id'],
'placeholder'=>'Select...',
'url'=>Url::to(['/calonpegawai/district']),
'params'=>[$model->fk_districs_id]
]
]) ?>
Add javascript in your view:
$script = <<< JS
$("#regency_id").change(function(){
$("#district-id").depdrop({
depends: ['regency_id'],
url: '/calonpegawai/district'
});
}).change();
JS; $this->registerJs($script);
Hope to help you.
Upvotes: 1