Pawan Pawan - 1 month ago 6
PHP Question

Yii2: Using Kartik Depdrop Widget?

Ok I am trying to use the Kartik Depdrop widget, all I am getting a white drop-down list that is values not showing in the dependent drop-down list.

I have a state model and a city model and I have it setup like this.

In _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(), [
'depends'=>['state_name'], // the id for cat attribute
'url'=> \yii\helpers\Url::to(['patient-entry/subcat'])

Then in model

public static function getCity($city_id) {

return $data;

Then in my controller

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'=>'']);
echo Json::encode(['output'=>'', 'selected'=>'']);

When I select the state field, the firebug console shows the data correctly like:


The city field drop-down is also shows as if it has been filled up with data, but only with white-spaces.

What I am doing wrong here?



Ok I found the solution, All the code is ok, actually the depdrop widget looks for the pair id and name like:

// 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>']
        // ]

Accordingly I have changed the code in the model



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

That's all and it is working fine now. Hope someone will find this useful.