Rendering a Symfony form field manually
Published on 2020-01-21 • Modified on 2020-01-21
In this snippet, we will see how to manually render checkboxes of a form with Twig. This can be useful when you have special things to display depending on the items. In this example, we group the choices with an arbitrary rule and we set different header size. As Ryan says on the Symfonycasts tutorial, don't do this until you have no other way to achieve what you need. This should always be an exception in your codebase.
{% trans_default_domain 'snippet' %}
{{ form_start(form) }}
{% for choice in form.my_field.vars.choices %}
{% if loop.index == 1 %}
<h3>{{ 'p72_1'|trans }}</h3>
{% endif %}
{% if loop.index == 3 %}
<h2>{{ 'p72_2'|trans }}</h2>
{% endif %}
{% if loop.index == 7 %}
<h4>{{ 'p72_3'|trans }}</h4>
{% endif %}
<label for="{{ form.my_field.vars.name }}_{{ choice.value }}">{{ choice.label|trans }}</label>
<input type="checkbox" id="{{ form.my_field.vars.name }}_{{ choice.value }}" name="{{ form.my_field.vars.name }}" value="{{ choice.value }}"/>
{% endfor %}
{% do form.my_field.setRendered() %}
{{ form_end(form) }}
HTML demo of the snippet
More on Stackoverflow Read the doc Random snippet