You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:27:04