9

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

1 Answer 1

7

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;
        }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your quick response! I expected to find the variables in the Length class, should've checked the LengthValidator class of course. Now I know that the variables can be declared in a customized ConstraintValidator.
you can get all the parameters for a specific error by calling ->getMessageParameters() on the error, these are the values that are inserted into the message after it is translated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.