如何在Yii2应用程序中的多个选择下拉列表中显示所选值?
I am working on Yii2. I am creating multiple select drop down using custom array like this.
In controller file:
$all_groups = Groups::find()->where(['=','group_created_by',$id])->orwhere(new Expression('FIND_IN_SET(:id_to_find, group_managers)'))->addParams([':id_to_find' => $id])->all(); // fetch all values
$selected_groups = Groups::find()->where(['=','group_users',$updateId])->orwhere(new Expression('FIND_IN_SET(:id_to_find, group_users)'))->addParams([':id_to_find' => $updateId])->all(); // getting selected values
$all_groups_array = [];
foreach ($all_groups as $group) {
$all_groups_array[$group->id] = ucfirst($group->group_name);
}
On render data on the view:
return $this->render('mngr_userupdate', [
'model' => $model,
'all_groups_array'=>$all_groups_array,
'case'=>$case,
'email_error' => 'false',
'applied_email' => '' ,
]);
so it is creating array like this:
Array
(
[11] => Mngr1 group
[14] => Mngr 11 Group
)
In vies file:
<?= $form->field($model, 'group_user[]')->dropDownList($all_groups_array,['multiple' => 'multiple']) ?>
It is working fine on create form for data insertion. but how to create array using which I can display selected values on update form.
Edit:
I just found that if I use it like
<?= $form->field($model, 'group_user[]')->dropDownList($all_groups_array,['multiple' => 'multiple', 'options'=>['14'=>["Selected"=>true],'11' => ["Selected"=>true]]]); ?>
then it will start display values as selected. i.e. I have to create array like
[
'14'=>["Selected"=>true],
'11' => ["Selected"=>true]
]
For this I am using loop like as follows:
foreach ($selected_groups as $key => $value) {
$sel_groups_array[$value] = '' // what should be there or else
}
How can I create this array using loop?
I have created solution of my question, In case if anyone has the such kind of problem then he can use the loop like as follows:
foreach ($selected_groups as $group) {
$sel_groups_array[$group->id] = array("selected"=>true);
}
and in the views file you can use the array for display selected multiple values as follows:
<?= $form->field($model, 'group_user[]')->dropDownList($all_groups_array,['multiple' => 'multiple','options' => $sel_groups_array]); ?>
Because the structure to display multiple selected values on update form, it should be like as follows:
$form->field($model, 'group_user[]')->dropDownList($all_groups_array,['multiple' => 'multiple', 'options'=>['14'=>["Selected"=>true],'11' => ["Selected"=>true]]]);
// here 14 and 11 I am using as example