[SOLVED] Roll back model attributes if fail to save or to validate

Dear everyone,

I need to roll back model’s attributes after fail in validate or save.

For example :

I have…


$model = new Person();


$model->setAttributes(array(

     'name' => 'John'

));


$model->save();

Then I do…


$model->setAttributes(array(

     'name' => 'Jonathan'

));


$model->save(); // This line failed! According to whatever validation rules I have.

But now the [color="#0000FF"]$model->name[/color] is ‘Jonathan’, I need the name ‘John’ back programmatically. (instead of let users fix it)

I know there is transaction roll back, but this is about attributes in model.

I have a solution in my mind for one.

Create another instance to copy $model and after failing in save or validate just copy them back.

But I’d like to know that if anyone have the same issue before? How you do guy solve it? Like what I mentioned above or something else.

Thanks in advance.

And when would you create another instance?

You need to save the "old" value so that you can get back if user enters wrong values… so the old values needs to be saved somewhere in the session or in the database…

I would rather go for creating another array to save data temporary and when system fails to save or to validate, I’ll use the temporary array to return old value.

Anyway thanks for your reply, I just need to know if there is a best practice out there which I don’t know yet.

When the users finish entering/editing the form and submit it… your previous variable are not available anymore… so… when will you create the temporary array?