Reputation: 70
I have a form that dynamically generates fields based on the entities in my database (my entities are courses). For each new course, it adds a form field to modify it's sort order. My question is, how can I dynamically show these individual form fields in my table of courses?
My form logic:
foreach ($entities as $id => $course) { //$id key included to show you courses key value
$formBuilder->add($course->getId(), 'text', array(
'data' => $course->getsortOrder(),
'label' => false,
'attr' => array('class' => 'sort' /*, 'style' => 'visibility:hidden;'*/ )
));
}
My jQuery that modifies the form fields:
$(document).ready(function () {
$(".records_list tbody").sortable({items: "tr"},
{stop: function(event, ui) {
$(".sort").each(function(index) {
$(this).val(index);
});
}
});
});
/* I tested the proper functionality of this jQuery by putting
<input type="text" class="sort" value="{{ entity.sortOrder }}">
into the <td> that sort order is in. I want to replace this with
something like {{ form_widget(form.{entity.id}) }} */
I can easily put:
{% for entity in entities %}
<td>
{% if( entity.id == 1) %}
{{form_widget(form.1)}} //1 is entity id
{% else if (entity.id == 2 ) %}
{{form_widget(form.2)}} //2 is entity id
{% else if (entity.id == 3 ) %}
{{form_widget(form.3)}} //3 is entity id
{% endif %}
</td>
{% enfor %}
But that is obviously not very dynamic. You add a new course, and it breaks.
It would be nice if I could say
{% for entity in entities %}
<td>
{% set course = entity.id %}
{{form_widget(form.course)}}
</td>
{% endfor%}
but sadly that does not work.
Any insight as to how to dynamically add these form fields into my sortOrder 's is appreciated.
Upvotes: 3
Views: 4133
Reputation: 1351
I'm not sure to understand what your are trying to do.
But, if you want to access dynamically a property onto an object or an array, you can use the attribute Twig function.
To you should try something like this in your template :
{% for entity in entities %}
<td>
{{ form_widget(attribute(form, entity.id)) }}
</td>
{% endfor%}
Upvotes: 7