Yii下拉列表空值为默认值

gro*_*ler 9 php yii drop-down-menu

我的_form模型中有一个下拉列表,我想添加一个空值(我想要默认值).我有以下内容:在_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'); ?>
Run Code Online (Sandbox Code Playgroud)

在模范国家:

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

即使我的空选项位于下拉列表的第一行,列表中的第一个国家/地区也显示为默认选项.

我试过了:

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

通过这种方式,我可以选择默认选项,但不能将其设置为空值,只是来自model:items的国家/地区.

任何的想法?

Ezz*_*zze 21

country_id打印下拉列表时,您确定模型的属性未设置为任何内容吗?如果$model实例是使用new Country()运算符创建的,而不是通过从数据库填充属性,则以下内容适用于我:

<?php echo $form->dropDownList(
    $model,
    'country_id',
    Country::items(),
    array(
        'empty'=>'--Select a country--')
    );
?>
Run Code Online (Sandbox Code Playgroud)


Bog*_*rym 12

阅读文档.有'提示'参数.

试试这个:

<?php
    echo $form->dropDownList($model,'country_id',Country::items(), array(
        'prompt' => '--Select a country--'
    ));
?>
Run Code Online (Sandbox Code Playgroud)

请在此处查看更多详细信息http://www.yiiframework.com/forum/index.php/topic/11195-how-to-edit-the-default-option-in-dropdownlist/