Search code examples
twigsymfony-2.7

How to iterate over subforms in Twig to display validation errors?


I want to iterate over all fields in my form and display the error (validation) message by mismatching. I use the following code and it works for all field which are located directly in the form object. For all fields which are located in a subform / merged form does this solution not work.

</table>
<div style=" height:180px; overflow:auto;">
<table class="neo-table">
<tbody>
  {% for children in form.children %}
    {% if children.vars.errors is defined %}
       {% for error in children.vars.errors %}
        <tr>
          <td>
           <strong> {{ error.message }}</strong>
          </td>
        </tr>
       {% endfor %}
     {% endif %}
    {% endfor %}
</tbody>
</table>

the picture should clarify the problem:

form structure

I get the error message from all fields which starts with the prefix fu1 but not from the fields with the prefix ses f.e the field sesOccupationMother2.

As well i dont get the Information when i use this piece of code:

{{form_errors(form.fu1KfPatientid.bSes)}}

or something like that:

{{form_errors(form)}}

i just get the Information when i write the FQN from the field like this:

{{form_errors(form.fu1KfPatientid.bSes.sesOccupationMother2)}}

Whats the reason for this behavour? Does somebody know a trick, how i can use my function and iterate about the errors with the subforms?

Thanks for supporting!


Solution

  • So now i wrote function, which does not look really nice but it works.

    {% for children in form.children %}
             {% if children.vars.errors is defined %}
                {% for error in children.vars.errors %}
                    <tr>
                      <td>
                        <strong> {{ error.message }}</strong>
                      </td>
                    </tr>
                  {% endfor %}
                {% endif %} 
                  {% for children in children.children %}
                    {% if children.vars.errors is defined %}
                      {% for error in children.vars.errors %}
                              <tr>
                                <td>
                               <strong> {{ error.message }}</strong>
                                </td>
                              </tr>
                        {% endfor %}
                      {% endif %} 
                         {% for children in children.children %}
                            {% if children.vars.errors is defined %}
                                {% for error in children.vars.errors %}
                                 <tr>
                                   <td>
                                    <strong> {{ error.message }}</strong>
                                </td>
                              </tr>
                           {% endfor %}
                           {% endif %} 
                    {% endfor %}
                {% endfor %}
            {% endfor %}