Yii2 dropDownList 标记选项被选中 [英] Yii2 dropDownList mark option selected

查看:21
本文介绍了Yii2 dropDownList 标记选项被选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用选定的值制作一个下拉列表,但仍然没有进展,下拉正在渲染,但始终选择第一个选项.

Hi i'm trying to make a drop down list with selected value but there is still no progress, drop down is rendenering but always first option is selected.

$company_id = (int) $params['company_id'];
$options = [
    'options' => [
         $company_id => [
            'selected' => 'selected',
            'label' => 'test'
        ]
     ]
];
echo $form->field($model, 'company_id')->dropDownList($companies_list, $options);

那个代码有什么问题?我编辑了我的代码,并在我的选项中设置了标签"=>测试",这有效,但仍然没有选择

whats wrong with that code? I edited my code and i set 'label' => 'test' in my option, and this works, but selected still not

找到了好的解决方案,在我在 renderSelectionOptions 方法中找到的框架代码中:

Ok solution found, in framework code i found in renderSelectionOptions method :

$attrs = isset($options[$key]) ? $options[$key] : [];
$attrs['value'] = (string) $key;
$attrs['selected'] = $selection !== null &&
    (!is_array($selection) && !strcmp($key, $selection)
    || is_array($selection) && in_array($key, $selection));

所以我需要做的就是:

$model->company_id = $company_id;

渲染前部分

推荐答案

仅供未来访问者注意:

如果您使用 ActiveForm,那么您的模型字段的值将用作选定值,但如果您不使用 ActiveForm 并使用 生成下拉列表Html helper 然后 dropDownList 函数也接受另一个参数 selection,您可以在其中传递要选择的值,如 文档

If you are using ActiveForm then value of your model field will be used as the selected value but if you are not using ActiveForm and generating dropdown list with Html helper then dropDownList function accepts another parameter selection as well, in which you can pass the value that you want to make selected, as mentioned in docs

这篇关于Yii2 dropDownList 标记选项被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆