Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 dropDownList mark option selected

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

like image 636
szapio Avatar asked Dec 08 '25 04:12

szapio


1 Answers

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

like image 191
Tahir Avatar answered Dec 11 '25 01:12

Tahir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!