【问题标题】:How can I show all errors in Twig?如何在 Twig 中显示所有错误?
【发布时间】:2021-07-07 04:47:09
【问题描述】:

我在 Symfony 5 中创建了一个表单,当验证错误时,如果错误为真,我希望在一个表单中显示所有错误,如下所示: 错误:

  • 错误 1
  • 错误 2
  • 错误 3 ...

我用:

{% if form_errors(form)|length %}
     <div>Errors:</div>
     {{ form_errors(form) }}
{% endif %}

但不起作用。

如何在 Twig 中做到这一点?

【问题讨论】:

  • |lenght 应该是 |length 除非您定义了自定义过滤器。

标签: forms symfony validation twig


【解决方案1】:

您使用以下显示所有错误

{# 
If the form is not valid then :
Note: in this case the form variable is : form
 #}
{% if not form.vars.valid %}
<ul>
    {# Loop through every form item #}
    {% for child in form.children %}
        {# Display the errors of the form item #}
        {%for error in child.vars.errors%}
            <li>{{error.message}}</li>
        {%endfor%}
    {%endfor%}
</ul>
{%endif%}

【讨论】:

  • 谢谢,但显示此错误:带有键“值、属性、表单、id、名称、全名、禁用、标签、标签格式、标签html、多部分、块前缀、唯一块前缀、 row_attr、translation_domain、label_translation_parameters、attr_translation_parameters、cache_key、c​​licked" 不存在。
【解决方案2】:

您可以在代码中使用它:

{% if not form.vars.valid %}
<div>Errors:</div>
    <ul>
        {% for error in form.vars.errors.form.getErrors(true) %}
            <li>{{ error.message }}</li>
        {% endfor %}
    </ul>
{% endif %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多