我使用了来自Kartik的Extension,用于创建依赖的下拉列表,称为DepDrop。
我的依赖架构Regencies-> District-> Villages
当创建动作时,一切正常,运行井,但是当更新动作时,在儿童下拉列表中不显示选定值。
这是我的观看代码:
<?= $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]
]
]) ?>
在这里我的控制器:
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'=>'']);
}
我的模特:
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;
}
答案 0 :(得分:1)
在您的视图中添加:&#39;数据&#39; =&gt; [$ key =&gt; $ 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]
]
]) ?>
在您的视图中添加javascript:
$script = <<< JS
$("#regency_id").change(function(){
$("#district-id").depdrop({
depends: ['regency_id'],
url: '/calonpegawai/district'
});
}).change();
JS; $这 - &GT; registerJs($脚本);
希望能帮到你。