dropDownList default item selected

I am having a hard time finding any information about how to have a specific item in a drop down list selected by default.

If I have is a drop down list as follows:




$form->dropDownList($activityModel, 'repeats', array('never'=>'Does not repeat', 'daily'=>'Daily', 'weekly'=>'Weekly','monthly'=>'Monthly', 'yearly'=>'Yearly')); 



and I want to make ‘Monthly’ the default selected value on page load, I am not sure how to do this. I know that you can do something like this to add a default selected value at the top of the list:




$form->dropDownList($activityModel, 'repeats', array('never'=>'Does not repeat', 'daily'=>'Daily', 'weekly'=>'Weekly','monthly'=>'Monthly', 'yearly'=>'Yearly'), array('empty'=>'Monthly'));



But this simply adds a new item with value ‘Monthly’ to the top of the drop down list, so now I have two options for ‘Monthly’ in the list. What if I want to select the ‘Monthly’ item in the drop down list by default on page load, rather than add a default selected item to the top of the list? Is there a way to do this in Yii? I just can’t seem to find any example code or clear documentation about how to accomplish this. I’ve already tried the following:




$form->dropDownList($activityModel, 'repeats', array('never'=>'Does not repeat', 'daily'=>'Daily', 'weekly'=>'Weekly','monthly'=>'Monthly', 'yearly'=>'Yearly'), 'htmlOptions'=>array('monthly'=>array('selected'=>'selected')));



but this just gives me the following error:

Parse error: syntax error, unexpected T_DOUBLE_ARROW

I’ve also tried:




$form->dropDownList($activityModel, 'repeats', array('never'=>'Does not repeat', 'daily'=>'Daily', 'weekly'=>'Weekly','monthly'=>'Monthly', 'yearly'=>'Yearly'), array('monthly'=>'selected'));



But nothing happens.

I’ve tried all kinds of combinations of code and arrays in the dropDownList, but can’t seem to get it working.

Can someone point me in the right direction? I feel like I am missing something small and simple, but I can’t for the life of me figure it out.

Someone please help!

The solution is pretty easy: set $activityModel->repeats to any value of the list. You can also specify a default value in the model class: public $repeats = ‘daily’;

Wow, that is pretty easy. Thanks a lot!

Andy, how about doing this for a multiple option dropdownList? I have one where in create action I selected many options and I want this options to appear selected in update action.

There is a way of doing $repeats[]=array(1=>value1…2=>value2…)?

Thanks a lot!

Another way to solve this is assigning a default value to the appropriate table in the database…just like what happened in this post.

Hello Andy, thanks for the reply. One more question: what if I want the selected option in the dropdownlist to be the ID passed via GET?

Thanks in advance!!!

If I understand you right, you need to assign an attribute’s value before creating a list:


$model->attribute = $_GET['ID'];