Reputation: 851
I am trying to display a list of courses with a checkbox allowing the user to select any number of courses from the list. I am new to Symfony and trying to follow the form approach but do not understand how to display additional attributes of an object beyond using the choice_label.
If I were just passing the course objects, I could simply use:
Template:
<form>
{% for course in courses %}
<div class="row">
<div><input type="checkbox" name="course[]" value="{{ course.id }}"></div>
<div>{{ course.name }}</div>
<div>{{ course.description }}</div>
<div>{{ course.semester }}</div>
</div>
{% endfor %}
</form>
Using the form builder, it seems my template would look like this:
{{ form_start(form) }}
<div class="row">
<div>{{ form_row(form.courses) }}</div>
</div>
{{ form_end(form) }}
How can I access these additional object attributes (name, description, etc.) within the form row? Is there a reason to use to the form builder in this case instead of the first 'by hand' approach? In summary, I need granular control of the object attributes within a given form row and the choice_label attribute alone does not seem sufficient. What is a potential solution?
Upvotes: 1
Views: 435
Reputation: 11
First, for accessing each option of the choice label, it's fairly simple... because the form.courses is an array. You can access individual checkbox by doing this :
{{ form_widget(form.courses[0]) }}
And you can use a loop to access them individually. And for customizing the rendering of your forms, you can use form_errors, form_label and form_help functions, so your final code will be something like this :
{{ form_start(form) }}
{{ form_errors(form) }}
{% for course in form.courses %}
<div class="row">
{{ form_widget(course) }}
{{ form_label(course) }}
</div>
{% endfor %}
{{ form_help(form.courses) }}
{{ form_end(form) }}
Note: The label is the key value in the array passed to the « choices » option in Form Builder.
Sources:
How to Customize Form Rendering : https://symfony.com/doc/current/form/form_customization.html
Upvotes: 1