How to change the message in buildRules [CakePHP 3]?

3.4k Views Asked by At

The function below is for being sure the e-mail from form is unique, if it's already in use a message is showed. I want to change this message.

public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->isUnique(['username']));
    $rules->add($rules->isUnique(['email']));
    return $rules;
}

I tried this way:

 public function buildRules(RulesChecker $rules)
 {
     $rules->add($rules->isUnique(['username']));
     $rules->add($rules->isUnique(['email']), 
         ['errorField' => 'email', 'message' => 'Este email já encontra-se em uso.']
     );
     return $rules;
}

It works but both messages are being showed, the default one and mine.

1

There are 1 best solutions below

1
On BEST ANSWER

When using that style of adding unique rules, you'll have to pass the message to the isUnique() calls second argument, ie

$rules->add($rules->isUnique(['email'], 'Este email já encontra-se em uso.'));

That is because you are technically creating nested callables this way ($rules->isUnique() creates one, and $rules->add() creates another one), and defining options in the add() call will cause them to be set in the outer callable, finally resulting in two messages being set, the one you've set for the outer callable, and the default one from the inner callable.

Basically the above is the shorthand for

$rules->add(new \Cake\ORM\Rule\IsUnique(['email']), [
    'errorField' => 'email',
    'message' => 'Este email já encontra-se em uso.'
]);

See also