how can i use a twig variable as a form field name?

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]) }}  

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.

Also worth reading on the same note:

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top