9

我的 _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'); ?>

在示范国家:

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

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

我试过了:

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

通过这种方式,我可以选择默认选项,但不能将其设置为空值,只是来自模型的国家:项目。

任何想法?

4

5 回答 5

22

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

<?php echo $form->dropDownList(
    $model,
    'country_id',
    Country::items(),
    array(
        'empty'=>'--Select a country--')
    );
?>
于 2013-04-17T11:08:17.170 回答
12

阅读文档。有“提示”参数。

尝试这个:

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

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

于 2013-04-17T11:13:51.053 回答
1

items你总是可以在你的方法中做类似 array_merge 的事情

public static function items()
{
return array_merge(array(''=>'--Select a country--'), CHtml::listData(Country::model()->findAllBySql(
                            'SELECT * from country'), 
                            'id', 'name'));
}
于 2013-04-17T11:24:11.520 回答
1

我相信您正在寻找:

echo $form->dropDownList($model,'country_id',Country::items(),array('prompt'=>''));
于 2013-04-17T11:30:41.710 回答
0

如果你使用 yiibooster 也许这会有所帮助

<?php echo $form->dropDownListGroup(
            $model,
            'kode_cuti_sub2',
            array(
                'empty'=>'--Select a country--',
                'widgetOptions' => array(
                    'data' => array('Something ...', 'Pilih Jenis Cuti'=>Chtml::listData(Cuti::model()->cuti_sub2(),'kode','jenis_cuti')),
                    'options' => array(
                        'placeholder' => 'Pilih NIP Pegawai',
                        'width' => '100%',
                    ),
                ),
                'wrapperHtmlOptions' => array(
                    'class' => 'col-sm-5',
                ),
            )
        ); ?>

就我而言,它有效

于 2015-06-26T02:12:38.217 回答