user3209287
user3209287

Reputation: 219

Modify $this->request->data in model CakePHP?

How can I modify $this->request->data from model in CakePHP. I tried it with code in model User :

public function beforeValidate($options = array()) {
    unset($this->request->data['User']['birthday']);
}

But it return errors :

Notice (8): Indirect modification of overloaded property User::$request has no effect

Warning (2): Attempt to modify property of non-object

If I use (model User) :

public function beforeValidate($options = array()) {
    unset($this->data[$this->alias]['birthday']);
}

It's ok, but after validate, when I tried print_r($this->request->data) in controller, I see birthday field that still exists in it.

Anyone can give me a solution for this, is different between $this->data and $this->request->data, thanks !!

Edit : My CakePHP version is 2.6.7 - newest version.

Upvotes: 3

Views: 1928

Answers (1)

drmonkeyninja
drmonkeyninja

Reputation: 8540

$this->request->data cannot be accessed from within the model. This data is only accessible from the controller. When you attempt to save data to a model from the controller (e.g. $this->User->save($this->request->data))) you are setting the User model's data attribute. In other words, this is happening:-

$this->User->data = $this->request->data;

So in your model's callback methods you can access the data being saved using $this->data and manipulate it as you have found in your beforeValidate():-

public function beforeValidate($options = array()) {
    // Unset 'birthday' from data being saved
    unset($this->data[$this->alias]['birthday']);
    return parent::beforeValidate($options);
}

Don't forget when using this callback to call the parent method and ensure that it returns a boolean. If it doesn't return true your data will not get saved!

If you manipulate $this->data in your model it will not affect $this->request->data but you can always access the model's data attribute from within the controller to see the changes. For example, in your controller after saving changes:-

// Output the User data
debug($this->User->data);

If you really want to alter $this->request->data then you need to do this from within the controller (presumably before the save), not the model:-

unset($this->request->data[$this->alias]['birthday']);

Just as a side note be careful of unsetting your data in the model callback's as it will do that everytime you try to save data (unless you disable the callback). So unsetting birthdaywould result in it never getting saved to your database.

Upvotes: 4

Related Questions