Getting specific error message in Twig that was ge

2019-09-16 14:37发布

问题:

I'm passing $errors to Twig, generated from this:

$insert = new MyEntity();
$insert->setTest1( 'testtesttest' );
$validator = $this->get('validator');
$errors = $validator->validate($insert);

...how do I get a specific error value, something like this if it worked?

{{ errors('field1') }}

...which should just return the error message, e.g. "That is not a valid email address" etc.

I know I can loop through to get all of them:

{% for err in errors %}
    {{ err.label }}: {{ err.value }}<br />
{% endfor %}

...but I just want one specific one

回答1:

You cant just access the fieldname of an array of validation-error objects directly. You have to search it by looping.

{% for error in errors %}
   {% if error.propertyPath = 'fieldname' %}
      {{ error.propertyPath }}: {{ error.message }}
   {% endif %}
{% endfor %}

But maybe you're better off just using ...

$errors = $validator->validateProperty($insert, 'fieldname);

... in your controller and just passing the list of errors for the one property into your template.



标签: symfony twig