Yii2 output for multiple selected values

I used the Yii2 drop-down select list, it works great when creating, but does not show me the selected values ​​when updating!

the 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 can I show multiple selected values ​​in a dropdown when I update my code?

+4
source share
2 answers

all your code is fine, you just need echoyour $ form → ...

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

or use <?= ?>in sight!

+6
source

Here is the solution:

The form

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

Controller:

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

public function actionUpdate($id)
{
    $model = $this->findModel($id); 
    $model->categories = explode(',', $model->categories);        
    ...
    if($model->load(Yii::$app->request->post()))
    {
         $model->categories = implode(",",$_POST['Company']['categories']);    
         ...
         $model->save()
    }
    return $this->render('update', [
                'model' => $model,                    
            ]); 
  }
+2
source

Source: https://habr.com/ru/post/1613598/


All Articles