Yii下拉列表默认为空值

zpqajqem  于 2022-11-09  发布在  其他
关注(0)|答案(5)|浏览(165)

我在my _form模型中有一个下拉列表,我想添加一个空值(我想作为默认值)。我有以下内容:
表单(_F):

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

这样我可以选择默认选项,但不能将其设置为空值,只能设置来自model:items的国家。
你知道吗?

amrnrhlw

amrnrhlw1#

当您打印下拉列表时,您确定您的模型的country_id属性没有设置为任何值吗?如果使用new Country()运算符创建$model示例,而不是通过从数据库填充属性来创建,则下面的方法对我有效:

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

hvvq6cgz2#

阅读文档。有'prompt'参数。
试试看:

<?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/

at0kjp5o

at0kjp5o3#

您总是可以在items方法中执行类似array_merge的操作

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

svgewumm4#

我相信您正在寻找:

echo $form->dropDownList($model,'country_id',Country::items(),array('prompt'=>''));
js81xvg6

js81xvg65#

如果你使用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',
                ),
            )
        ); ?>

在我的情况下,它是有效的

相关问题