选择Yii2 dropDownList标记选项 [英] Yii2 dropDownList mark option selected
问题描述
我正在尝试使用选定的值下拉列表,但是仍然没有任何进度,下拉列表是rendenering,但始终选择第一个选项。
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);
该代码有什么问题?我编辑我的代码,我在我的选项中设置'label'=>'test',这样做可以,但是选择仍然不是
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;
在渲染部分
推荐答案
只是一个未来访客的注释:
Just a note for future visitors:
如果您使用 ActiveForm
您的模型字段将用作所选值,但如果您不使用 ActiveForm
并生成下拉列表,其中包含 Html
帮助然后 dropDownList
函数接受另一个参数选择
,您可以在其中传递要选择的值,如文档 所述)
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屋!