如何使Symfony / Bootstrap复选框错误显示在form_widget之外?

时间:2018-07-21 11:24:18

标签: html symfony twig bootstrap-4

我不确定该如何解释... :) 我正在使用symfony,twig和bootstrap在我的网站上制作基本注册表格。 我在最后有一个复选框,用户必须勾选该复选框以接受条款和条件。该复选框的标签包含Bootstrap(或Twig)转义的HTML(标签),因此我必须在复选框旁边使用自定义标签:

<div class="row align-items-center"> <!-- this is a workaround, may not be best practise -->
              {{ form_errors(form.acceptTerms) }}
              {{ form_widget(form.acceptTerms, { 'attr': {'form.acceptTerms.errors': ' '} }) }}
                <label class="form-check-label" for="acceptTerms">I have read and accepted the <a href="terms.php">Terms and Conditions</a></label>
            </div>

Bootstrap会将标签呈现为form_widget树枝元素的一部分,而不是form_label的一部分,并且在出现错误时,form_error也会呈现在form_widget内。因此,以前,我的标签只能以纯文本显示,即html <a>标签对用户是可见的。但是当然,由于我要显示自定义标签以及包含标签的小部件,因此我必须将小部件标签设置为''(空字符串),因此现在仅显示一个标签。 这项工作正常进行,直到出现错误(即用户没有在方框中打钩,因此无法注册)。 然后错误显示在我的自定义标签旁边的form_widget中(它们位于引导row div中),当我希望错误在上面时,最终将标签推到右侧标签。如您所见,我尝试在其上方添加{{form_errors(form.acceptTerms)}},但这只会在标签上方和旁边显示错误。上面的代码就这样显示:

ERROR you must accept the terms and conditions!
[ ] ERROR you must accept the terms and conditions!I Accept the **Terms and Conditions**

然后这就是我想要的样子:

ERROR you must accept the terms and conditions!
[ ] I accept the **Terms and Conditions**

这似乎应该是一件很容易的事情,我不知道为什么这么难。 我需要以某种方式阻止引导程序在form_error内呈现form_labelform_widget。 谢谢

1 个答案:

答案 0 :(得分:0)

在Symfony 4.1中,引导表单主题已更新为符合WCAG 2.0标准。结果,该字段的错误不再显示在form_errors中,而是显示在您的form_label中。如果您将小部件和标签分开,则会注意到。 有关此更改的更多信息,请参见here

为了解决您的问题,只需摆脱form_error(您不再需要它),而仅使用form_labelform_widget。如果这不能满足您的需求,或者您不喜欢symfony 4.1中bootstrap 4表单的新行为,则可以始终使用较旧的表单主题,也可以创建自己的主题。

如果您决定创建自己的表单主题,请确保将文件twig.yaml更新为以下内容:

twig:
form_themes:
    - form/custom_form_theme.html.twig

在这种情况下,您的自定义表单主题位于templates/form/custom_form_theme.html.twig