The problem with model validation messages in my application: 1) They need to be human-readable and may vary depending on module. 2) They need to be translated in several languages.
Here comes the solution. One may ask why don't override Model's getMessages method? The answer is it'll be less configurable and (critical for me) wouldn't affect ValidationFailed::getMessages() as I prefer to throw exceptions on save() failed.
Hope it will be useful for someone, other solutions are welcome ;-)
config/services.php:
...
$di['messages'] = function () {
$messages = require __DIR__ . '/messages/en.php';
return new \Phalcon\Translate\Adapter\NativeArray(array(
'content' => $messages,
));
};
$di['modelsManager'] = function () use ($di) {
$eventsManager = new \Phalcon\Events\Manager();
$eventsManager->attach('model', function ($event, $model) use ($di) {
if ('onValidationFails' === $event->getType()) {
if ($t = $di->get('messages')) {
foreach ($model->getMessages() as $message) {
$message->setMessage(
$t->_($message->getMessage(), $model->toArray()));
}
}
}
});
$modelsManager = new \Phalcon\Mvc\Model\Manager();
$modelsManager->setEventsManager($eventsManager);
return $modelsManager;
};
models/User.php
<?php
class User extends \Phalcon\Mvc\Model
{
public $login;
const E_EXISTS = 'User exists';
public function validation()
{
$this->validate(new Phalcon\Mvc\Model\Validator\Uniqueness(array(
'field' => 'login',
'message' => self::E_EXISTS,
)));
return !$this->validationHasFailed();
}
}
messages/en.php
<?php
return array(
User::E_EXISTS => 'User %login% already exists',
);