Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 dropdown multiple selected values

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?

like image 422
Muhammad Shahzad Avatar asked Oct 29 '15 06:10

Muhammad Shahzad


Video Answer


1 Answers

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!

like image 180
Mohsen Avatar answered Sep 28 '22 03:09

Mohsen