[英]How to display selected values in multiple select dropdown in a Yii2 app?
I am working on Yii2. 我正在研究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: 在vies文件中:
<?= $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. 然后它将启动所选的显示值。 ie 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.