【问题标题】:Make a Yii Dropdown default value be NULL使 Yii Dropdown 默认值为 NULL
【发布时间】:2014-06-05 18:58:08
【问题描述】:

我的 Yii 表单中有一个使用 CActiveForm->dropDownList 创建的下拉列表。

我使用数组('empty'=>'Please select one')作为未选择时设置值的方式。

该字段被约束到另一个表,但它被设置为允许 NULL。当 Yii 显示 MySQL 错误时,它说:

integrity constraint violation: 1452 Cannot add or update a child row: a foreign
key constraint fails (`imi_sales`.`ss_project`, CONSTRAINT
`fk_project_product_type` FOREIGN KEY (`product_type_id`) REFERENCES 
`ss_product_type` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

它还显示插入到 ss_project.product_type_id 的值是 ''。如果我将 SQL 复制出来并将其更改为 NULL,它就可以工作。如何让 Yii 将其设置为 NULL?

【问题讨论】:

    标签: php mysql yii foreign-keys


    【解决方案1】:

    beforeSave()方法中加入如下代码:

    public function beforeSave(){
        if(parent::beforeSave()){
            if(empty($this->product_type_id)) {$this->product_type_id=NULL;}
            return true;
        }
    }
    

    这样,你在保存新记录之前告诉 Yii,检查product_type_id 的值是否为空('')。如果是,设置为NULL

    【讨论】:

    • 谢谢。我想过这个问题,但假设它必须是一个足够普遍的问题,也许我只是做错了什么,奇怪,但这会起作用。干杯。
    【解决方案2】:

    所选答案有效,但我相信这更优雅。

        /**
         * @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(
    ....................
                array('product_type_id', 'default', 'setOnEmpty' => true, 'value' => null),
    ....................
            );
        }
    

    【讨论】:

      猜你喜欢
      • 2012-01-18
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 2017-09-11
      相关资源
      最近更新 更多