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;

		if(isset($_POST['Post']))

		{

			$model->attributes=$_POST['Post'];

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

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

			if($model->save())

				$this->redirect(array('index'));

		}

Any ideas?

Have a look here

http://www.yiiframework.com/doc/api/1.0.9/CModel#afterValidate-detail

/Tommy

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

  parent::afterValidate($scenario);

}



/Tommy

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().

http://www.yiiframework.com/doc/api/1.0.9/CActiveRecord#beforeSave-detail

Example




protected function beforeSave()

{

  // your code probably goes here

  return parent::beforeSave();

}



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

http://www.yiiframework.com/doc/api/1.0.9/CActiveRecordBehavior

/Tommy

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?