Yii2:使用Kartik Depdrop Widget?

Paw*_*wan 2 php yii-extensions yii2

好的我正在尝试使用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'])
]
]);
  ?>
Run Code Online (Sandbox Code Playgroud)

然后在模型中

    public static function getCity($city_id) {
        $data=\app\models\City::find()
       ->where(['state_name'=>$city_id])
       ->select(['id','city_name'])->asArray()->all();

            return $data;
        }
Run Code Online (Sandbox Code Playgroud)

然后在我的控制器中

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'=>'']);
        }
Run Code Online (Sandbox Code Playgroud)

当我选择状态字段时,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":""}
Run Code Online (Sandbox Code Playgroud)

城市字段下拉菜单也显示为已填充数据,但仅包含空格.

我在这做错了什么?

谢谢.

Paw*_*wan 13

好的我找到了解决方案,所有的代码都没问题,实际上depdrop小部件寻找对,idname喜欢:

// 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>']
        // ]
Run Code Online (Sandbox Code Playgroud)

因此我更改了模型中的代码

->select(['id','city_name'])->asArray()->all();

with

->select(['id','city_name AS name'])->asArray()->all();
Run Code Online (Sandbox Code Playgroud)

这就是全部,现在工作正常.希望有人会觉得这很有用.