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.
$this->request->datacannot 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 theUsermodel'sdataattribute. In other words, this is happening:-So in your model's callback methods you can access the data being saved using
$this->dataand manipulate it as you have found in yourbeforeValidate():-Don't forget when using this callback to call the parent method and ensure that it returns a boolean. If it doesn't return
trueyour data will not get saved!If you manipulate
$this->datain your model it will not affect$this->request->databut you can always access the model'sdataattribute from within the controller to see the changes. For example, in your controller after saving changes:-If you really want to alter
$this->request->datathen you need to do this from within the controller (presumably before the save), not the model:-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.