Entryton Entryton - 11 days ago 13
PHP Question

Yii 2 dropDownList - Default value not being selected

I'm using Yii 2 ActiveForm, trying to make option 7 "default".

To do this, I have to use the options array, but when I do so, my html attribute "selected" is not being rendered at all when viewing the HTML source. I get no errors.

If I use other options, such as "label" it works as intended.

$form->field($model, 'date')->dropDownList($months, [
'options'=>array(
'7' => ['label' => 'JULY', 'selected'=>true],
),
]);


According to the docs, any "valid" option is accepted, I assume "selected" is valid as it's a HTML dropdown list?

This is what is generated:

<select id="log-date" class="form-control" name="Log[date]">
<option value="1">JANUARY</option>
<option value="2">FEBRUARY</option>
<option value="3">MARCH</option>
<option value="4">APRIL</option>
<option value="5">MAY</option>
<option value="6">JUNE</option>
<option value="7" label="label works fine">JULY</option>
<option value="8">AUGUST</option>
<option value="9">SEPTEMBER</option>
<option value="10">OCTOBER</option>
<option value="11">NOVEMBER</option>
<option value="12">DECEMBER</option>
</select>

Answer
  1. It was answered here: Yii2 dropDownList mark option selected. You need to set the date attribute:

    $model->date = 7;
    $form->field($model, 'date')->dropDownList($months);
    
  2. There is also discussion from developers: dropDownList pre Selection not rendering 'selected' They propose that you either define default value for attribute in init() method or set it directly in view (this is same as answer above). I also do it like this

    $model->priority = $model->isNewRecord ? 2 : $model->priority;
    $form->field($model, 'priority',[
           'options'=>['class'=>'col-xs-12 col-md-3']
        ])->dropDownList($priorityList)
    
Comments