php - Yii dropDownList 默认值

标签 php yii

我有这个代码:

echo $form->dropDownList($model, 
                 'defaultPrinterId', 
                  CHtml::listData(Printer::model()->findAll(), 'id', 'name'), 
                  array('prompt' => '-- None--')); 

这给了我一个像这样的下拉列表:

<select id="LabelType_defaultPrinterId" name="LabelType[defaultPrinterId]">
    <option value="">-- None --</option>
</select>

但是,当表单发布时,它会向我的表添加一个值,其中 defaultPrinterId 为 0。除此之外,我如何将其设置为 null,因为它是一个可为 null 的字段?

最佳答案

如果您想严格遵循 MVC,那么与模型相关的值的验证应该在模型中完成。

可以这样实现:

/**
 * @return array validation rules for model attributes.
 */
public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        //rules rules rules...
        array('defaultPrinterId', 'default', 'setOnEmpty' => true, 'value' => NULL),
        //rest of the rules
    );
}

关于php - Yii dropDownList 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10899371/

相关文章:

if语句中的php return语句

yii - git 忽略 Yii 数据库细节

php - 将 Facebook PHP SDK 实现到 Yii Framework 中的最佳方式

php - 由于构造函数,Yii 模型 isNewRecord false

php - ZF2 - ServiceManager 和 'aware' 接口(interface)

php - laravel 从数据库检索数据需要太多时间

php - 如何删除 jsondecode 中的特定值

sql - 在 yii 中如何使用电子邮件字段查找用户 ID

php - 检查两个 MySQL 表中是否存在值

php - 无法在 64 位 linux、php5.4 上为 apache2 加载 AMQP