DepDrop Widget of Kartik. The dependent dropdown display the array is ' '

I’m Trying to use DepDrop Widget of Kartik. However, the dependent dropdown does not display the array properly.
my _form

<?= $form->field($model, 'permanent_province') ->dropDownList(Province::getProvince(), ['id' => 'province_id']) ?> <?= $form->field($model, 'permanent_district')->widget(DepDrop::classname(), [ 'options' => ['id' => 'district_id'], 'pluginOptions' => [ 'depends' => ['province_id'], 'url' => Url::to(['district/sub']) ] ]); ?>

my Controller

public function actionSub()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$out = [];
if (isset($_POST[‘depdrop_parents’])) {
$parents = $_POST[‘depdrop_parents’];
if ($parents != null) {
$district_id = $parents[0];
$out = District::getDistrict($district_id);
return [‘output’ => $out, ‘selected’ => ‘’];
}
}
return [‘output’ => ‘’, ‘selected’ => ‘’];
}

my model

public function getDistrict($district_id)
{
return District::find()
->select([‘name’])
->where([‘id_province’ => $district_id])
->asArray()
->all();
}
output

Phpmyadmin, I’m Run SQL query/queries on the table is normal

SiteController.php

public function actionSubcat() 
{
$out = [];
if (isset($_POST['depdrop_parents'])) {
    $parents = $_POST['depdrop_parents'];
    if ($parents != null) {
        $cat_id = $parents[0];
        $out = self::getSubCatList($cat_id); 
        return Json::encode(['output'=>$out, 'selected'=>'']);
    }
}
return Json::encode(['output'=>$out, 'selected'=>'']);
}

public static function getSubCatList($postalcode_id) {
   //find all the streets in the postal area 
    $data=\frontend\models\Productsubcategory::find()
   ->where(['productcategory_id'=>$postalcode_id])
   ->select(['id','name AS name'])->asArray()->orderBy('name')->all();
   return $data;
   
}

A few things you can try:

  1. Json::encode your output. Don’t forget to include the following at the top of your file.

      use yii\helpers\Json;
    
  2. A reminder: the old examples that kartik used included echos in the controllers. Using echo’s is no longer allowed in the newer versions of Yii2.

  3. Try using ‘name AS name’

  4. Move your function getDistrict into your controller.

1 Like