Symfony2 Validator message: Which variables are available?

我们两清 提交于 2019-12-22 04:15:31

问题


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:


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;
        }


来源:https://stackoverflow.com/questions/27703395/symfony2-validator-message-which-variables-are-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!