Simple check if form field has errors in Twig template

后端 未结 10 1632
一个人的身影
一个人的身影 2021-01-30 08:11

In Twig template I check if a field has an error like this:

{% if form.points.get(\'errors\') is not empty %}

Is there any method like:

相关标签:
10条回答
  • 2021-01-30 08:48

    For deeper form customization I do:

    <div class="form-group {% if form.MYFORMINPUT.vars.valid==false %}has-error{% endif %}">
    //some twisted divs
    {{form_label(form.MYFORMINPUT)}}
    {{form_widget(form.MYFORMINPUT)}}
    </div>
    

    Sf2.5

    0 讨论(0)
  • 2021-01-30 08:49

    That method does not exist. I typically do {% if form.points.vars.errors|length %}.

    0 讨论(0)
  • 2021-01-30 08:55

    You can also check for errors when overriding field rendering:

    {% block field_row %}
    {% spaceless %}    
        <div class="control-group {% if errors %}error{% endif %}">
          {{ form_label(form) }}
          <div class="controls">
            {{ form_widget(form) }}        
            {{ form_errors(form) }}        
          </div>
        </div>    
    {% endspaceless %}
    {% endblock field_row %}
    
    0 讨论(0)
  • 2021-01-30 08:57

    Since an empty array resolves to false, you can shorten your existing check to

    {% if form.WIDGET_NAME.get('errors') %}
    
    0 讨论(0)
  • 2021-01-30 08:58

    I had a similar problem, but form.points doesn't exist in my twig templates.

    I had to get the number of errors in the controller, then pass it into my templates as a variable. $form->getErrors() does not behave as you might expect in your controller though. See this SO question for a function that will get the form errors correctly.

    0 讨论(0)
  • 2021-01-30 09:00

    The right code is (for Symfony 3.4):

    {% if form.vars.errors|length %}
    
    0 讨论(0)
提交回复
热议问题