Sunday, June 30, 2013

Re: Get old record in beforeSave when updating (doing a $this->find() inside beforeSave callback)



On Saturday, 29 June 2013 19:53:49 UTC+2, Vanja Dizdarević wrote:
When updating a row, I wish to read the "old" data before saving the current record.

Here's a simplified example:

Controller code:
$this->User->save(['id' => 3, 'username' => 'a-new-username']);

Model code:
class User extends AppModel {
   public function beforeSave($options){
       //is it an update?
       if (isset($this->data[$this->alias][$this->primaryKey])) {
            //read record
            $oldData = $this->findById($this->data[$this->alias][$this->primaryKey]);
              //^^^ here's the problem! ^^^
            if ($oldData[$this->alias]['username_update_count'] >= 3){
               return false;
            }
            else {
              $this->data[$this->alias]['username_update_count'] = $oldData[$this->alias]['username_update_count'] + 1;
            }
       }
   }
}

The problem is, that $this->findById (or any other READ operation) fills the current $this->data with the read data

If by "READ operation" you mean a find call (you refer to findById - a find) - that is quite simply not true.

If you call the method Model::read however, it will populate $this->data.

AD

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments: