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

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

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

      

But it returns errors:

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

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

If I use (User model):

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

      

This is ok, but after checking when I tried print_r ($ this-> request-> data) in the controller, I can see the birth field that still exists in it.

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

Edit: my CakePHP version is 2.6.7 - the newest version.

+3


source to share


1 answer


$this->request->data

cannot be obtained from within the model. This data is only available from the controller. When you try to store data in a model from a controller (for example $this->User->save($this->request->data))

), you set the User

model attribute data

. In other words, this happens: -

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

      

So, in your model callback methods, you can access the stored data with $this->data

and manipulate it as you 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 you use this callback to call the parent method and make sure it returns a boolean value. If it does not return true

, your data will not be saved!



If you're manipulating $this->data

in your model, it won't affect $this->request->data

, but you can always access the model attribute data

from inside 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 change $this->request->data

, you need to do it from within the controller (presumably before saving), not the model: -

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

      

As a side note, be careful to disable your data in the model callback, as this will do this every time you try to save data (unless you disable the callback). Thus, disabling birthday

will result in it never being saved to your database.

+4


source







All Articles