在从 Symfony2 Validator 生成的 Twig 中获取特定的错误消息 [英] Getting specific error message in Twig that was generated from Symfony2 Validator

查看:23
本文介绍了在从 Symfony2 Validator 生成的 Twig 中获取特定的错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 $errors 传递给 Twig,由此生成:

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

推荐答案

您不能直接访问验证错误对象数组的字段名.你必须通过循环来搜索它.

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.

这篇关于在从 Symfony2 Validator 生成的 Twig 中获取特定的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆