CakePHP localized form validation

I’ve noticed a lot of techniques to handle localized form valaidation messages. Some even require hacking core Cake classes. Lots of people are still wondering on how to set it up as easy as possible. And still the answers available in the cookbook are allthough correct, not the best or smartest way to implement this. Some time ago I came across a nice way how to get this working. The only thing you need to do is overwrite a model function.

Assuming that L10n is properly set up.

When a field does not pass a validation rule, the following function is called.

Model::invalidate($field, $value = true);

This message takes as a first parameter the model field which didn’t pass validation, and the error message as $value. The only thing to do is thus translate that message, this can easily be done by overwriting the method. notice the function __().

//in your AppModel
function invalidate($field, $value = true)
{
    return parent::invalidate($field, __($value, true));
}

Now that our function is properly setup you can easily change the error messages for the fields in your models.

var $validate = array(
    'username' => array(
        'rule' => 'isUnique',
        'message' => 'FIELD_UNIQUE'
    )
);

In your .po file you can then add a msgid "FIELD_UNIQUE" and it is translated automaticly by the L10n class.