Activeform dropwown doesn't render default selected

Hello,

Can some1 explain where is the issue, that makes this not working? Thanks a lot.


<?= $form->field($model, 'requested')->dropDownList([ 'Yes' => 'Yes', 'No' => 'No', ], ['options' => ['No' => ['selected' => true]] ]) ?>

This is generated by Yii


<select id="uservacationdays-requested" class="form-control" name="UserVacationDays[requested]">

<option value="Yes">Yes</option>

<option value="No">No</option>

</select>

You have to modify the value in your model :




public function actionCreate() //Or whatever

{

  $model = new Something([

    'requested' => 'Yes'

  ]);

  //or : $model->requested = 'Yes'

  

}



tip : Use constants in your model class




class Something extends ActiveRecord

{

  const REQUESTED_YES = 'Yes';

  const REQUESTED_NO = 'No';

  ...

}



No, the question is why is not the default is ‘No’

No is not default because it is not set to be default properly.


options=>[] 

are HTML options and


 'no'=>['selected' => true]

is not valid HTML.

You are telling the browser something it doesn’t understand so it doesn’t work.

You can’t set the selected value in a dropdown list <select> portion it has to be in the <option> section to be valid HTML.

To properly select an option in html it would have to be


<select id="uservacationdays-requested" class="form-control" name="UserVacationDays[requested]">

<option value="Yes">Yes</option>

<option selected="selected">No</option>

</select>

So do do the Same thing in Yii2 you have to do what Timmy said (except it’s in the controller)


public function actionCreate() //Or whatever

{

  $model = new Something([

    'requested' => 'Yes'

  ]);

  //or : $model->requested = 'Yes'

  

}




class Something extends ActiveRecord

{

  const REQUESTED_YES = 'Yes';

  const REQUESTED_NO = 'No';

  ...

}




An alternative would be to make no first in the list


<?= $form->field($model, 'requested')->dropDownList(['No' => 'No','Yes' => 'Yes' ], ['options' => []]) ?>