Let’s say we want to write a Dropdownlist using Yii, for example:
[code]
<?php
echo $form->dropDownList($model,’product_id’, array(‘1’ => ‘Monitor’, ‘2’ => ‘Keyboard’), array(‘prompt’=>’–select–‘, ‘onchange’=>"javascript:combine_product_id();", ‘id’=>’tipodecliente_lst’));
?>
[/code]
How can we set a default selected value? There are several methods. I’m gonna begin with the two methods that I like the least (I don’t like them, but nonetheless they are illustrative), and the 3rd one is the method I recommend.
1. Changing the model’s attribute, but it has the problem of not being the best solution if the dropdownlist is multiselect. Besides, it is a model level solution for an interface issue: unless we are talking about a very sensitive decision, sometimes the default-selection is a matter of visualization only, sometimes it is a programmer’s whim to leave a default selection, but it doesn’t deeply affect the database, nor the model itself, nor the application gravely, so I think that the solution should be in the views layer.
2. Creating a default value in the table, is another solution that is being proposed in other threads. This is worse, I think: it uses a database-level solution for something that is a matter of visualization (read the argument of point 1).
3. A views level solution, is using the “options” entry in the array of htmloptions, I read it in the CHtml Dropdownlist (DropDownList Detail) documentation, but I applied it for an ActiveForm Dropdownlist. So in this example, if the reader wants the item with key value “2” to be selected by default, she/he should use:
[code]
<?php
echo $form->dropDownList($model,’product_id’, array(‘1’ => ‘Monitor’, ‘2’ => ‘Keyboard’), array(‘prompt’=>’–select–‘,’onchange’=>"javascript:combine_product_id();", ‘id’=>’product_list’, ‘options’=>array(2=>array(‘selected’=>’selected’))
));
?>
[/code]
Default selected value in a dropdownlist in Yii – Web Developement resourses
[…] http://www.saidur-rahman.com/default-selected-value-in-a-dropdownlist-in-yii/ […]