Yii2 dropdown multiple selected values

Muhammad Shahzad picture Muhammad Shahzad · Oct 29, 2015 · Viewed 32.9k times · Source

I used Yii2 multiple selection dropdown , it is working fine at create but not showing me selected values on update!

Form:

       $form->field($model, 'categories[]')            
         ->dropDownList($model->CategoryDropdown,
         [
          'multiple'=>'multiple'
          'class'=>'chosen-select input-md required',              
         ]             
        )->label("Add Categories");    

Model:

public function getCategoryDropdown()
{
        $listCategory   = Category::find()->select('ID,name')
            ->where(['is_subcategory' => 'Yes'])
            ->andWhere(['status' => 'active','approved' => 'active'])
            ->all();
        $list   = ArrayHelper::map( $listCategory,'ID','name');

        return $list;
}

Controller:

 public function actionCreate(){
 ...
     $model->categories = implode(",",$_POST['Company']['categories']);
    ...
    return $this->render('create', [
            'model' => $model,           
        ]);
 }

public function actionUpdate($id)
{
    $model = $this->findModel($id);    

    echo $model->categories; //  1,2,4,5  values already assigned
    ...
    return $this->render('update', [
                'model' => $model,                    
            ]); 
  }

Database:

1,2,4,5

How I can show multi selected values in dropdown when I update my recored?

Answer

mohsen picture mohsen · Oct 29, 2015

all your code is ok just need echo your $form->...

echo $form->field($model, 'categories[]')            
     ->dropDownList($model->CategoryDropdown,
     [
      'multiple'=>'multiple',
      'class'=>'chosen-select input-md required',              
     ]             
    )->label("Add Categories"); 

or use <?= ?> in view!