While trying to write a simple login function for a user model today I came across a small gotcha that it is not apparent at first.
In CakePHP 1.1 if you want to manually validate a model you would write:
if ($this->Model->validates($this->data)){
//success
}
However in CakePHP 1.2 this throws a nice deprecated warning:
Warning (512): (Model::validates) Parameter usage is deprecated, set the $data property instead [CORE/cake/libs/model/model.php, line 1660]
I first tried just an empty validates() expecting it to use Controller::data, however this was appearing to pass validation. Not good when the entire form was empty with VALID_NOT_EMPTY’s on every field. A quick look-see in the source of model.php reveals that Model::invalidFields() expects Model::data to be populated.
As pointed out by nate in the comments my original solution is not recommended.
The updated solution is to use:
$this->Model->set($this->data);
if ($this->Model->validates()){
// success
}
Direct manipulation of the Model’s $data property is not recommended. Use the set() method.
Thanks nate, I have updated the post to reflect your recommendation.
Thanks for this post Geoff – saved me a lot of head scratching!
Wow, I have looked for this answer all evening. Thanks for posting!
Geoff, thanks!
This saved me from giving cake the boot. Tired of the deprecated stuff and lack of docs.
Wow. Huge thanks. Definitely just spent about an hour stuck on this.
how can i validate a contact form?
i have a model Contact – but no Database
so i just put in the model var $useTable = false;
but with the above code, it always shows validation errors – no matter if i typed something in or not in the contact form:
model Contact:
var $validate = array('name' => array(
'empty' => array(
'allowEmpty' => false,
'required' => true,
'message' => 'Please insert your name',
)
),
'email' => array(
'required' => array(
'required' => true,
'message' => 'Please insert your email',
)
),
'title' => array(
'alphanumeric' => array(
'allowEmpty' => false,
'message' => 'Please insert title',
)
)
);
Controller Contact:
var $name = 'Contact';var $helpers = array('Html', 'Form');
var $components = array('Email');
function index() {
if (!empty($this->data))
{
$this->Contact->set($this->data);
if ($this->Contact->validates())
{
echo 'done';
}
View Index
Contact me:
create('Contact',array('controller'=>'contact','action'=>'index'));?>
input('name');
echo $form->input('email');
echo $form->input('title');
echo $form->input('message',array('type'=>'textfield'));
echo $form->input('attachments');
?>
end('Submit');?>
[...] Por otra parte, el uso del método validates de la clase Model, que comprueba si los campos de un registro satisfacen las reglas de validación que se definen en el modelo, también ha cambiado. Esto lo explican aquí. [...]
[...] 注意:英語のサイトです。 http://lemoncake.wordpress.com/2007/06/26/validation-gotcha-in-cakephp-12/ [...]