Phalcon\Validation\Message: Overwrite the standard

Hello again :)

currently I'm sticking on a new problem regarding the validation messages. The standard validation messages interface expects or contains the following attributes:

  • type
  • message
  • field

But internally we need a further attribute named "code". I found out that I can overwrite the "Phalcon\Validation" and add a new message class so that I can reach that, but I would like to keep all the available functionalities from Phalcon but only overwrite the standard message system, so that for example the model would also take this new class. Is there any option where I can set the message class?

Thanks!



84.6k

Hi, there is no such way to tell Phalcon\Validation use a different class for messages. You can convert the messages implementing an afterValidation event in your validation class:

class MyValidation extends Phalcon\Validation
{

    /**
     * Executed after validation
     *
     * @param array $data
     * @param object $entity
     * @param Phalcon\Validation\Message\Group $messages
     */
    public function afterValidation($data, $entity, $messages)
    {
        $customMessages = [];
        foreach ($messages as $message) {
            $customMessages[] = new MyMessage($message->getMessage(), $message->getType(), 'code');
        }
        $this->_messages = $customMessages;
    }

}

Then use this class

<?php

use Phalcon\Validation\Validator\PresenceOf,
    Phalcon\Validation\Validator\Email;

$validation = new MyValidation();

$validation->add('name', new PresenceOf(array(
    'message' => 'The name is required'
)));

$validation->add('email', new PresenceOf(array(
    'message' => 'The e-mail is required'
)));

$failed = $validation->validate($_POST);
if (count($failed)) {
    foreach ($validation->getMessages() as $message) {
        echo $message->getCode(), ' ', $message, '<br>';
    }
}