Ignoring field on Update using setOnEmpty

I have a model, on which I set a field on INSERT, which is good. However, on UPDATE, I don’t want to overwrite some of the existing fields in the table, because they’ll never change. So I’ve looked into rules, and setup the following rule that should NOT alter the ‘createdby_id’ on update, as it doesn’t need overwriting. But it appears to be ignored and overwrites it with a null value anyway - am I doing anything wrong?


 public function rules() {

        // NOTE: you should only define rules for those attributes that

        // will receive user inputs.

        return array(

            array('createdby_id','default','setOnEmpty'=>false,'on'=>'update')

        );

    }

Can you post your code where you set the createdby_id? Is it in an event (beforeSave) or in the controller? I’m assuming it isn’t a field in the _form.

Cheers,

Matt

A common solution is use the beforeSave event in the model. Make sure createdby_id isn’t a field in form and it’s not a safe attribute.




public function beforeSave()

    {

        if ($this->getIsNewRecord())

        {

            $this->createdby_id = Yii::app()->user->id;

        }

        

        return parent::beforeSave();

    }



Cheers,

Matt

A simple solution is to make the field unsafe for updates. In this example we don’t want to update the ‘createdby’ attribute.

public function rules()


{


	// NOTE: you should only define rules for those attributes that


	// will receive user inputs.


	return array(


		:


                    :


	        array('createdby', 'unsafe', 'on'=>'update')


	);


}