使Yii下拉菜单默认值为NULL


Make a Yii Dropdown default value be NULL

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

我使用数组('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?

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"

选择的答案有效,但我认为这个更优雅。

    /**
     * @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),
....................
        );
    }