0
votes

I have a dropdown in my Yii form created with CActiveForm->dropDownList.

I am using the array('empty'=>'Please select one') as the way to set the value when nothing is selected.

The field is constrained to another table, but it is set to allow NULL. When Yii shows the MySQL error, it says:

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)

It also shows that the value being inserted into ss_project.product_type_id is ''. If I copy the SQL out and change it to NULL, it works. How can I have Yii set it to NULL?

2

2 Answers

2
votes

Add the following codes into beforeSave() method:

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

By this, you tell Yii before saving new record, check whether product_type_id value is empty('') or not. If yes, set it NULL.

2
votes

The selected answer works but I believe this is more elegant.

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