好的,我正在尝试使用Kartik Depdrop小部件,但我得到了一个白色下拉列表,该列表中的值没有显示在从属下拉列表中。
我有一个州模型和一个城市模型,我有这样的设置。
在_form.php 中
$catList=ArrayHelper::map(app'models'State::find()->all(), 'id', 'state_name' );
echo $form->field($model, 'state')->dropDownList($catList, ['id'=>'state_name']);
echo $form->field($model, 'district_city')->widget(DepDrop::classname(), [
'options'=>['id'=>'district_city'],
'pluginOptions'=>[
'depends'=>['state_name'], // the id for cat attribute
'placeholder'=>'Select...',
'url'=> 'yii'helpers'Url::to(['patient-entry/subcat'])
]
]);
?>
然后在模型中
public static function getCity($city_id) {
$data='app'models'City::find()
->where(['state_name'=>$city_id])
->select(['id','city_name'])->asArray()->all();
return $data;
}
然后在我的控制器
public function actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = 'app'models'PatientEntry::getCity($cat_id);
echo Json::encode(['output'=>$out, 'selected'=>'']);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}
当我选择状态字段时,firebug控制台会正确显示数据,如:
{"output":[{"id":"172","city_name":"Along"},{"id":"173","city_name":"Bomdila"},{"id":"174","city_name":"Itanagar"},{"id":"175","city_name":"Naharlagun"},{"id":"176","city_name":"Pasighat"}],"selected":""}
城市字段下拉列表也显示为已填充数据,但仅包含空白。
我在这里做错了什么?
谢谢。
好的,我找到了解决方案,所有的代码都是好的,实际上depdrop小部件查找id
和name
对,比如:
// the getSubCatList function will query the database based on the
// cat_id and return an array like below:
// [
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]
因此,我更改了型号中的代码
->select(['id','city_name'])->asArray()->all();
with
->select(['id','city_name AS name'])->asArray()->all();
仅此而已,现在一切都很好。希望有人会发现这个有用。
您也可以:
echo $form->field($model, 'district_city')->widget(DepDrop::classname(), [
'options'=>['id'=>'district_city'],
'pluginOptions'=>[
//// change default 'nameParam'=>'name' to
'nameParam'=>'city_name',
'depends'=>['state_name'], // the id for cat attribute
'placeholder'=>'Select...',
'url'=> 'yii'helpers'Url::to(['patient-entry/subcat'])
]
]);
?>
将"nameParam"更改为"city_name"