Yii2中带optgroup的Html::dropDownList如何设置选中值?
解决方案
你当前的核心问题是$selection参数传递错误:
- Yii2的
Html::dropDownList()的$selection参数仅需匹配目标选项的value值,和上层的optgroup分组无关,不需要传入分组的键值 - 你代码中写的
['Page 1']['107141']属于无效的PHP语法,自然无法生效
修改后的正确代码
echo Html::dropDownList( 'criteria', // 直接传入要选中的选项对应的key值即可,比如要选中Q9对应项就传107141 '107141', [ 'Page 1' => [ '107145' => 'Q1: some text', '107141' => 'Q9: some text', '107142' => 'Q10: some text', '107143' => 'Q11: some text', '107164' => 'Q14: some text', ], 'Page 2' => [ '107195' => 'some text', ], ], [ 'prompt' => [ 'text' => 'Choose criteria', 'options' => [] ], 'id' => 'criteriaSelector', 'class' => 'criteriaSelector', 'required' => 'required', ] );
补充说明
如果要默认选中Page 2下的选项,直接传入107195即可,不需要附加Page 2的分组标识。如果是开启了多选的下拉框,$selection参数传入需要选中的value组成的数组即可,示例:$selection = ['107141', '107195']。
内容的提问来源于stack exchange,提问作者Littlebob
相关产品推荐
相关产品推荐

