Checkbox selected YII2 dropDownList
Hi i am trying to make a dropdown with a selected value but no progress has been made yet, the dropdown is rendenering but the first option is always 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);
What's wrong with this code? I edited my code and I set 'label' => 'test' to my variant and this works but the selected one is not yet
Ok's solution is found in the framework code 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 I have to do is:
$model->company_id = $company_id;
before the render section
source to share
Just a note for future visitors:
If you are using ActiveForm
then the value of your model field will be used as the selected value, but if you are not using ActiveForm
and generating the dropdown with Html
helper then the function dropDownList
takes another parameter selection
in which you can pass the value you want to make the selected as specified in docs
source to share