Alter form data prior to save()

Hi There,

Probably really easy to do but im not quite sure the best way??? I’d like to manipulate and change my form data after validation and before save() using active record.

I have a custom function that validates the data. But then I get a conflict from the validation rules if I try to change it.

For example…

		$model=new Post;




			$model->str1 = $model->filter($model->str1);

			$model->str2 = $model->filter($model->str2);




Any ideas?

Have a look here


Hi, thanks for that Tommy.

However, I’m still not exactly sure how to implement it into my controller / model.

Are you able to provide an example? Or general idea…

Something like this (in your model):

protected function afterValidate($scenario)


  // your code probably goes here




fibler, did you edit your first post, now providing an example? I didn’t notice before.

Perhaps I was wrong. Your other options are to call validate() yourself, do some processing, followed by save(false). If you just want to change what is written to the database you can use beforeSave().


protected function beforeSave()


  // your code probably goes here

  return parent::beforeSave();


A behavior would also be an appropriate option for the filtering.


Hey I didn’t see your second post… im still trying to figure it out. I’ll have a look at beforeSave and behavior and i’ll let you know. Thanks

Hey so I got it to work with if($model->validate()) and then save(false).

Thanks heaps for your help.

Also, I had a look more closely at behaviors and the available functions like beforeSave and afterValidate. The only thing is, im not exactly sure how to call a behavior from a controller when processing the form data.

Are you able to provide an example?