Yii2 dropdown multiple selected values

人盡茶涼 提交于 2019-12-23 12:01:48

问题


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?


回答1:


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!




回答2:


Here is solution:

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,                    
            ]); 
  }


来源:https://stackoverflow.com/questions/33407291/yii2-dropdown-multiple-selected-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!