what does beforesave mainly used for?why run after Model validate?

The problem I’m facing is that I want to change Model’s attribute value before save it, so I use beofreSave() method to do this, but when I call save() method, not the save(false) method, because I need It to check the Model’s rules. I will get error in Model’s validate() method.

Model code:


public function beforeSave($insert) {

        if ( parent::beforeSave($insert) ) {

            $this->goods_price = $this->goods_price * 100;

            $this->shipping_price = $this->shipping_price * 100;

            $this->order_amount = $this->order_amount * 100;

            $this->total_amount = $this->total_amount * 100;

            return true;

        }

        return false;

    }

Rules




[[ 'goods_price', 'shipping_price', 'order_amount', 'total_amount'], 'integer'],






$model = new Model();

$model->goods_price = 9.5; //I use beforeSave() to make the value be an integer

$model->save(); //will get error  "goods_price must be an integer"



So, I want to know how to user beforeSave() and what’s the common scene to use it.

thanks for every reply.

Hi James,

If you want to change a value before the validation takes place you could use:

beforeValidate() instead of beforeSave()

beforeValidate = Will be executed before the validation of the model takes place.

beforeSave = Will be executed after validation, but before the model is saved.

Best Regards

Thanks a lot! beforeValidate() fit me better. ^_^