Home > Software engineering >  Symfony 6 - Access CollectionType fields in Twig Template
Symfony 6 - Access CollectionType fields in Twig Template

Time:06-02

I have a Symfony 6 project, where I us a CollectionType in a Form.

This CollectionType is called "variants" and has three fields. Lets call them:

  • Field_1
  • Field_2
  • Field_3

If I render this CollectionType in my Twig template with {{form_row(form.variants)}} all three fields of the CollectionType are rendered underneith.

However, I would like to to separate each of the fields of the CollectionType in a own column next to each other. But how dow I access the fields?

I have tried to access the fields via {{form_row(form.variants.Field_1)}} but obviously that did not work.

I am happy about any ideas :)

CodePudding user response:

you were close.

CollectionType is an array - as it can hold multiple sets of the type.
If you only have one set try

{{ form_row(form.variants[0].Field_1) }}
{{ form_row(form.variants[0].Field_2) }}
{{ form_row(form.variants[0].Field_3) }}

CodePudding user response:

Thanks to Rufinus again.

I used that information and the remark from vinceAmstoutz and did the creation in a foor loop:

{% for variant in form.variants %} 
<div >
       <div >
            {{ form_row(variant.Field_1) }}
       </div>
       <div >
            {{ form_row(variant.Field_2) }}
       </div>
       <div >
            {{ form_row(variant.Field_3) }}
       </div>      
</div>
{% endfor %} 
  • Related