select item inside dropdownlist


inside the _form view of my create/update User controller action I have a static dropdownlist that on create action should be set to empty value and on update action to the $model value.

I’ve first tried this way:

<?php echo $form->dropDownList($model,'IsActive',array(""=>"Select","1"=>"Active","2"=>"Not Active")); ?>

the problem is that the default selected item is "1"=>"Active". But I want it to be ""=>"Select".

So I’ve tried:

<?php echo CHtml::dropDownList('IsActive',"",array(""=>"Select","1"=>"Active","2"=>"Not Active")); ?>

this time it works well at least in the create action. but it is not a good workaround end it won’t work for the update scenario where a link with the model attribute “IsActive” should be set.

Which is the right method to accomplish my task?

you have to setup eather

<?php echo CHtml::dropDownList('IsActive',0,array("Select","1"=>"Active","2"=>"Not Active")); 


<?php echo $form->dropDownList($model,'IsActive',array("Select",array("1"=>"Active","2"=>"Not Active"))); ?>


thank for your contrib.

the CHtml::dropDownList example doesn’t help much because you set the value of the selected value to 0 but it should be dynamic.

the CActiveForm->dropDownList example doesn’t render as I’d like:


<option value="">Select</option>

<option value="1">Active</option>

<option value="2">Not Active</option>




<option value="0">Select</option>

<optgroup label="1">

<option value="1">Active</option>

<option value="2">Not Active</option>



in first my example you have to setup value if you wont the default value be the select,

its have to be dynamicly ?, why then you setup

array("Select","1"=>"Active","2"=>"Not Active")

in your dropdown that is not dynamic.

in the second case i know that option group, because i setup first value as a string , and the seconds as array group, if you dont wont otpgroup replace with this

array("Select","1"=>"Active","2"=>"Not Active")

Your code is OK…

check the database for the default value for the field isActive… if you have defined the field isActive with a default value 1 then when creating a new model that attribute get the value 1…

so in the actionCreate… after $model=new YourModel()… you can set $model->isActive=’’; (or null)…

or use unsetAttributes()


take your first example, the selected value could be null in the case of an action Create or be a given value (1 or 2) in the case of an update action.

the solution with CActiveForm->dropDownList should be the right way to handle this because it automatically set the selected value against the model value.

But your example has the same inconvenient that I outlined in my first post: when the IsActive value is null the selected item should be "Select" and not "Active" like in your and mine ex.

thank you mdomba,

you’re right. the key was the default value set in my table value.

I’ve use the $model->unsetAttributes and all is working now.