Search code examples
symfonysymfony-2.1formbuilder

Can I repeat a Symfony form in a loop with Twig, or do I have to build it manually?


I am totally new to Symfony and Twig; just yesterday I was thrown into a legacy project that uses them.

I have a list, produced by a template loop, of Orders, each order having a priority from 1-5.

I want to add a single dropdown Select to each Order row which submits a form updating that Order's priority and refreshes the page.

My question is, can I use Symfony's buildForm in conjunction with this architecture? For now I have the following form constructed manually. Is it even possible to build a series of identical forms like this with Twig?:

{% for order in orders %}
<form method="post" action="{{ path('change_priority') }}" style="margin: 0; padding: 0;">
    <div class="form-group">
        <select name="priority" style="width: 35px; height: 20px;" onchange="this.form.submit()">
            <option value="1" {% if order.currentBody.priority == 1 %} selected {% endif %}>1&nbsp;&nbsp;- Low</option>
            <option value="2" {% if order.currentBody.priority == 2 %} selected {% endif %}>2&nbsp;&nbsp;- Normal</option>
            <option value="3" {% if order.currentBody.priority == 3 %} selected {% endif %}>3&nbsp;&nbsp;- High</option>
            <option value="4" {% if order.currentBody.priority == 4 %} selected {% endif %}>4&nbsp;&nbsp;- Critical</option>
            <option value="5" {% if order.currentBody.priority == 5 %} selected {% endif %}>5&nbsp;&nbsp;- No Priority</option>
        </select>
        <input name="order_id" value="{{order.serial}}" type="hidden" />
    </div>
</form>
{% endfor %}

And here is an image of what I'm after. Changing the priority of any of the Order row items changes that Order's priority and then refreshes the page.

enter image description here


Solution

  • you have to add them in the form type. You can not do that in your twig template. If you render a field with something like {{ form_row(form.select) }}, it will be flagged as displayed and will not be rendered a second time, even if you call {{ form_row(form.select) }} again.