如何在Yii2应用程序的多选下拉列表中显示选定的值? [英] How to display selected values in multiple select dropdown in a Yii2 app?
问题描述
我正在研究Yii2。我正在使用这样的自定义数组创建多个选择下拉列表。
I am working on Yii2. I am creating multiple select drop down using custom array like this.
在控制器文件中:
$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);
}
在视图上渲染数据:
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
)
竞争文件:
<?= $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.
编辑:
我刚刚发现,如果我像
<?= $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
}
如何创建
推荐答案
我已经创建了我的问题的解决方案,以防万一有人遇到此类问题,可以使用如下所示的循环:
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
这篇关于如何在Yii2应用程序的多选下拉列表中显示选定的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!