的Yii2:使用Kartik Depdrop小部件?
作者:互联网
好的,我尝试使用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和名称,例如:
// 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();
仅此而已,现在一切正常.希望有人会发现这个有用.
标签:yii-extensions,php,yii2 来源: https://codeday.me/bug/20191012/1898540.html