问题
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