Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translating Custom Validator messages with parameters

I have symfony2 custom validator with definition:

// Nip.php

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class Nip extends Constraint
{
    public $message = 'This value %string% is not a valid NIP number';
//...

This is validator code:

// NipValidator.php

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class NipValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {

        $stringValue = (string) $value;

        $nip = preg_replace('/[ -]/im', '', $stringValue);
        $length = strlen($nip);

        if ($length != 10) {
            $this->context->addViolation(
                $constraint->message,
                array('%string%' => $value)
            );

            return;
        }
//...

and my translation files:

// validators.pl.yml

validator.nip: %string% to nie jest poprawny nip

service definition:

// services.yml

services:
    validator.nip:
        class: BundlePath\Validator\Constraints\NipValidator
        tags:
            - { name: validator.constraint_validator, alias: validator.nip }

I tried to replace $constraint->message with 'validator.nip' but this only displays 'validator.nip' as string and it is not resolved to translated message.

CustomValidator works good, the only problem is with enabling translations. I've read docs from symfony.com about constraint translations but this is for standard validators not the custom one.

like image 994
Paweł Madej Avatar asked Mar 01 '14 10:03

Paweł Madej


1 Answers

I think the issue is in how you've defined your message key and structured the validations translation domain.

Your custom nip constraint message would be better as a translation key:

$message = error.nip.invalidNumber;

The translation file should read:

error:
    nip:
        invalidNumber: %string% to nie jest poprawny nip

You've defined a service alias that is the same as actual service name (validator.nip). I'm not sure if this would cause an error, but to be safe I would set the alias as app_nip_validator.

Finally, in your custom validator, remove the return and change how you build your violation.

        if ($length != 10) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('%string%', $value)
                ->addViolation();

            // return;
        }
like image 68
mark Avatar answered Oct 16 '22 21:10

mark