Search code examples
symfonytwigsilex

Twig and Silex, generating dynamic forms


I'm trying to generate a form on Twig using two for loops to generate the names and every form element. For some reason I'm getting some expression problem, but really can't find the issue. Maybe somebody can help.

{% for l in 1..line %}
<div class="row">
    {% for r in 1..row %}
    {% set form_name = "name_l_"~l~"_r_"~r~"_a" %}

    <div class="col-md-{{ cols }}">
      {{ form_label(form.~form_name, "Line: "~ l ~" total") }}
      {{ form_widget(form.~form_name, { attr: { 'class': 'form-control' }}) }}
    </div>
    {% endfor %}
</div>
{% endfor %}

Solution

  • You cannot append dynamic variables like that to access members of the object. You need to change:

    form.~form_name
    

    to this:

    form[form_name]
    

    which will achieve what you are looking for.