TimSparrow
TimSparrow

Reputation: 939

How can I use a twig variable as a form field name

I have a form template which has a repeated block for several similar form fields. It is used as follows:

{# form_template.html.twig #}
{{ include ('company-select.html.twig', {field: 'companiesInclude'})
{{ include ('company-select.html.twig', {field: 'companiesExclude'})
{{ include ('company-select.html.twig', {field: 'companiesLinked'})

Now I have a company select template, which looks as follows:

{# company-select.html.twig  (simplified, the actual template is much more complex) #}
<div class="form form-field selector" id="{{ field }}">
  {{ form_label(form.field) }}
  {{ form_widget(form.field) }}    

</div>

The way it is, the template fails, because 'field' is not a property of the FormView class.

How can I make the template interpolate the twig variable into the form_xxx function call as an actual field name?

Upvotes: 2

Views: 1707

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39334

A property of an object or an array element in twig can either be accessed via the dot notation (.) or via the square bracket one ([]).

If your property happens to be a twig variable, you will need to use the later form.

So in your case:

  • form_label(form[field])
  • form_widget(form[field])

Your code in company-select.html.twig ending up being:

<div class="form form-field selector" id="{{ field }}">
  {{ form_label(form[field]) }}
  {{ form_widget(form[field]) }}  
</div>

This is, in a really simplified example, testable here.

Note that, in a more complex flavour, you can also use the attribute function

., []: Gets an attribute of a variable.

Source: https://twig.symfony.com/doc/3.x/templates.html#other-operators
Also worth reading on the same note: https://twig.symfony.com/doc/3.x/templates.html#variables

Upvotes: 4

Related Questions