0
votes

I'm using a DropDownlist a select2 and a Depdrop with Yii2,

This is my form:

    <?php   $empresa = ArrayHelper::map(Companies::find()->all(),'company_id', 'company_name');
            echo $form->field($model, 'companies_company_id')->dropDownList($empresa, ['id'=>'company_id']); ?>

    <?php   echo $form->field($model, 'branches_branch_id')->widget(DepDrop::classname(), [
            'type'=>DepDrop::TYPE_SELECT2,
            'options'=>['id'=>'branch_id'],
            'select2Options'=>['pluginOptions'=>['allowClear'=>true]],
            'pluginOptions'=>[
                'depends'=>['company_id'],
                'placeholder'=>'Seleccionar sucursal...',
                'url'=> $base,
            ]
        ]);   
    ?>

this is my model:

public static function getBranches($branch_id)
{
    $data=Branches::find()
   ->where(['companies_company_id'=>$branch_id])
   ->select(['branch_id','branch_name'])->AsArray()->all();
    //$data2 = ArrayHelper::map($data, 'branch_id','branch_name');
    //var_dump($data[0]);
    //exit;
    if(empty($data))
    {
        return $data;
    }else
    {
        return $data[0];    
    }

}

this is my controller:

public function actionSubcat()
{
  $sucursal = [];
  if (isset($_POST['depdrop_parents'])) {
      $parents = $_POST['depdrop_parents'];

      if ($parents != null) {
          $id_branch = $parents[0];
          $Branch = new Branches();
          $sucursal = $Branch->getBranches($id_branch);
          //$Branch->getBranches($cat_branch);

          //ArrayHelper::map(Branches::find()->all(), 'branch_id', 'branch_name');

          //ArrayHelper::map(Branches::find()->all(), 'branch_id', 'branch_name');//self::getSubCatList($branch_id);

          echo Json::encode(['output'=>$sucursal, 'selected'=>'']);
          return;
        }
      }
      echo Json::encode(['output'=>[], 'selected'=>'']);
}

enter image description here

1
added an answer see if it helps - Muhammad Omer Aslam

1 Answers

0
votes

You need to change your model function getBranches(), if you see into the DOCS it says that you need to return the results for the dropdown list in the following format

// [
//    ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
//    ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]

Whereas what you are returning does not make any sense

if(empty($data))
{
    return $data;
}else
{
    return $data[0];    
}

What is the point of returning $data after checking that it is empty? anyways
your function should be changed to the following and it will start working

public static function getBranches($branch_id)
    {
        $data=Branches::find()
       ->where(['companies_company_id'=>$branch_id])
       ->select(['branch_id','branch_name'])->all();

         $arr = [];
         foreach ($data as $branch) {
            $arr[] = ['id' => $branch->branch_id, 'name' => $branch->branch_name];
        }
        return $arr;
    }