How to save a model object before updating it?

Hi all,

I have two tables, table A and table B:

Table A has the following fields:




id, title, body, lastupdated



and table B has those fields:




id, tblAid, title, body, lastupdated



What I want to do is that when the admin updates table A, the former record would be saved on table B.

For example:




* before updating table A*

[TableA] 1234, "new medicine trials", "<p>There is an increased [...]</p>", "2010-01-10"

* after updating table A*

[TableA] 1234, "New Medical Trials are underway", "<p>There is an increased [....]</p>", "2011-05-17"

[TableB] 1, 1234, "new medicine trials", "<p>There is an increased [...]</p>", "2010-01-10"



How do I do that in yii?

I am new to yii as well so I can’t be 100% of help but I can point you to the right direction.

Any model that inherits the class CActiveRecord has a method called beforeSave() that is called before a table is being updated.

Having said that, on Table A model

you would implement the beforeSave() method:




protected function beforeSave()

{

  $tableB = new TableB();

   

  //my guess is that the Table B id is auto_increment

  $tableB->tblAid = $this->id;

  $tableB->title = $this->title;

  $tableB->body = $this->body;

  $tableB->lastupdated = $this->lastupdated;


  $tableB->save();

}

Then the update function should do the rest for TableA

Again not 100% sure this will work but I think it should. You can also getAttributes() and setAttributes() on a CActiveRecord class but I don’t know how that would work with two id’s. Perhaps somebody else could help you with that. I hope it works and it was useful.

BeforeSave() is called just before saving the new data… so $modelA is already changed by the user…

if you want in $modelB the original values of $modelA you need to "remember" those values before the user edits them…

you can use session for that… and then in beforeSave assign it to the $modelB

Hmm the object has acquired the updated values so I can’t do anything, that’s the problem actually :( (I thought of beforeSave as well)

Interesting, I’ll try it, thanks.

Isn’t it possible to create another instance of modelA to retrieve the current values?

Well it worked with session, but if you have any other ideas you are welcome :)

That is true, so we are getting the values that are already sent to the model.

What if you do this:


$tblARow = self::model->findByPk($this->id);

and then do the rest that I suggested.

ie:


$tableB->tblAid = $tblArow->id;

That way you get the data from the db before the update has been applied.