Hi.
Why don't you save $this->data in another var before calling findById()?
Something like this:
class User extends AppModel {
public function beforeSave($options){
//is it an update?
if (isset($this->data[$this->alias][$this->primaryKey])) {
//read record
$newdata = $this->data;
$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 = $newdata;
$this->data[$this->alias]['username_update_count'] =
$oldData[$this->alias]['username_update_count'] + 1;
}
}
}
}
Is there any issue doing this?
--
Renato Freire
On Sat, Jun 29, 2013 at 2:53 PM, Vanja Dizdarević <[email protected]
> 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, which ruins the current update.
> So my gut tells me to instantiate a new User model inside the beforeSave
> (not optimal) or to somehow use the DataSource directly without all the
> callbacks and Model instantiation.
>
> The real scenario really has to be inside the beforeSave callback, because
> the logic is required for every modification.
>
> Thanks!
>
> --
> 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 [email protected].
> To post to this group, send email to [email protected].
> Visit this group at http://groups.google.com/group/cake-php.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>
--
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/groups/opt_out.