Yii2 dropDownList mark option selected

女生的网名这么多〃 提交于 2019-12-10 10:18:06

问题


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

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));

so all what i need to do is :

$model->company_id = $company_id;

before rendering section


回答1:


Just a note for future visitors:

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




回答2:


Please try this

for ($x = 1; $x <= 40; $x++) {
       if ($x=="1"){
            $items[$x] = $x." week";
        }else{
            $items[$x] = $x." weeks";
        }
    }
$weeks=28;
<?= Html::dropDownList('s_id', $selection = $weeks, $items, ['prompt' => '--Choose Week--','class'=>'form-control']) ?>


来源:https://stackoverflow.com/questions/27108609/yii2-dropdownlist-mark-option-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!