views:

203

answers:

1

Okay, this is driving me nuts. I’m working through the IBM CakePHP Tutorial, and in the first part, I’m at the section where the author is introducing validation rules for form input:

www.ibm.com/developerworks/opensource/tutorials/os-php-cake1/section5.html#N107E3

For the life of me, I can’t figure out what’s happening in this line of code:

$this->invalidate('username_unique');

According to the CakePHP documentation, the Model::invalidate() method takes as its first parameter a string that specifiies “The name of the field to invalidate”. How is “username_unique” the name of the field to validate? Looks to me like it should be just plain old “username”. But incredibly enough, the author’s code works, and mine doesn’t when I change “username_unique” to “username” (or even “User.username”), so I’m thinking there might be a serious flaw in the documentation (or very possibly, with me).

[FWIW, I can see that the CakePHP 1.25 provides a better means of doing validation, but I still find it troubling that what seems to be a well-documented method doesn't seem to be doing what it advertises, and I want to understand why the tutorial code works.]

Can anyone shed any light on this?

+4  A: 

The "magic" is actually in the $form in this case.

When calling $this->invalidate('username_unique'), Cake takes a note that the field username_unique is invalid. The fact that this field does not actually exist is irrelevant.

Now, take another look at the actual $form field (slightly reformatted):

echo $form->input('username', array(
    'after' => $form->error('username_unique', 'The username is taken. Please try again.')
));

It's outputting a normal form field, but "manually" places an error() output after the form field. $form->error('username_unique', $message) means "if there's an error for the field username_unique, output the message $message". So you're actually marking an imaginary field as invalid and are manually outputting an error message for this imaginary field.

And actually, that's a load of outdated cr*p you should forget right away. There's a built-in syntax for multiple validation rules per field, so you can test for character length and uniqueness at the same time and even get different error messages for each error type. There's even a built-in isUnique rule, so you won't even have to code a manual uniqueness test.

deceze
Thank you *so* much for the response! I had at one point reached this very conclusion, but gave it up since it seemed so insane. And I've already incorporated multiple validation rules into my project!Thanks again!
Steve
It *is* pretty insane indeed. I don't know how IBM can stand for this nonsense. :o)
deceze