我知道如何验证以及如何检索错误消息。 但是如何通过属性获取特定的错误输入?
不喜欢这样:
{% for error in errors %}
<li>{{ error.message }}</li>
{% endfor %}
我的意思是这样的:
getError($errors, 'myProperty');
这样的事情可能吗?
我使用验证器,但不使用表单类。我有 \ Symfony \ Component \ Validator \ ConstraintViolationListInterfac e - with 所有错误消息的数组。
我很遗憾没有在Twig上下文中...我需要它以便聪明..我想直接显示特定字段的错误消息,如下所示:
<label for="city">{getError($errors, 'myProperty')}</label>
<div class="form-group">
<input class="form-control" name="city" id="city" placeholder="City *" type="text">
</div>
答案 0 :(得分:1)
Validator
- 基于想法:因此,如果您有权访问Validator
课程, 可能 可以执行以下操作:
$validator->atPath('myField')->getViolations();
会返回ConstraintViolationListInterface
,但由于atPath
调用,它应该只返回一部分违规行为。
必须说,我自己从未尝试过,但听起来确实有效。
基于Form
的解决方案,对您来说不是很有用 Form
类使用方法getErrors()
方法:
public function getErrors($deep = false, $flatten = true)
在您的示例中,您可以致电:
form.myField.getErrors()
或通过变量:
{% set varWithFormName = "myField" %}
form[varWithFormName].getErrors()
希望这会有所帮助......
答案 1 :(得分:1)