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

+3


source to share


2 answers


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

+9


source


Please, try



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']) ?>

      

0


source







All Articles