Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Validator message: Which variables are available?

At this moment I am implementing validation using the Symfony Validator component using Annotations in my Entity class.

The Symfony documentation shows you can use certain placeholders to pass variables through a message and these messages can be translated by the Translator component.

So for example, it's possible to write the following annotation:

/**
 * Assert\Length(
 * min = 5,
 * max = 10,
 * minMessage = "Title too short: {{ limit }}",
 * maxMessage = "Title too long: {{ limit }}"
 */
 protected $title;

This works fine, but I was wondering what kinds of placeholders are available to you? Is it possible to create custom placeholders?

I know that the {{ value }} placeholder exists (and works), but it's not on the documentation page of Symfony on how to use the Length validation.

I would like to use a placeholder tag like {{ key }} or {{ name }} to pass through the technical name of the field (in this case "title"), so i can write my minMessage as minMessage = "{{ field }} too short: {{ limit }}"

I tried to check the standard components for Symfony to see how these placeholders are handled, but I cannot find a proper list of variables that are available to me.

Please help me! T_T

like image 897
StackOverflowUser Avatar asked Dec 30 '14 10:12

StackOverflowUser


1 Answers

If you check out the code for the LengthValidator you posted as an example you can see that these "variables" are just static strings that are replaced inside their own Validator class.

As such, all of them are custom, which is possibly also why there isn't a list available.

The class:

https://github.com/symfony/Validator/blob/master/Constraints/LengthValidator.php

Relevant snippet:

if (null !== $constraint->max && $length > $constraint->max) {
            $this->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->maxMessage)
                ->setParameter('{{ value }}', $this->formatValue($stringValue))
                ->setParameter('{{ limit }}', $constraint->max)
                ->setInvalidValue($value)
                ->setPlural((int) $constraint->max)
                ->setCode(Length::TOO_LONG_ERROR)
                ->addViolation();
            return;
        }
like image 91
Erik Avatar answered Nov 16 '22 03:11

Erik