Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii Dropdown List Empty Value as Default

I have a dropdownlist in my _form model and I want to add a empty value (which I want as default). I have the following:

In _form:

<?php echo $form->labelEx($model,'country_id'); ?>
<?php echo $form->dropDownList($model,'country_id',Country::items(),array('empty' => '--Select a country--')); ?>
<?php echo $form->error($model,'country_id'); ?>

In Model Country:

public static function items()
{
    return CHtml::listData(Country::model()->findAllBySql(
                        'SELECT * from country'), 
                        'id', 'name');
}

Even my empty option is in the first row in dropdownlist, the 1st country in list shows as default.

I tried:

<?php echo $form->dropDownList($model,'country_id',
    Country::items(),array('empty'=>'--Select a country--',
                           'options'=>
                             array(
                               '3'=>array('selected'=>'selected')
                                 )
     )); 
?>
    

In this way I can choose the default option, but cant set it to empty value, just countries that came from model:items.

Any idea?

like image 745
groovekiller Avatar asked Apr 17 '13 10:04

groovekiller


1 Answers

Are you sure that country_id property of your model is not set to anything when you print the dropdown list? The following works for me if $model instance is created using new Country() operator but not by populating properties from database:

<?php echo $form->dropDownList(
    $model,
    'country_id',
    Country::items(),
    array(
        'empty'=>'--Select a country--')
    );
?>
like image 95
ezze Avatar answered Oct 18 '22 09:10

ezze