Let's say I am using the Symfony Form Component to render a simple form with only two fields (username and email)
I am rendering both fields with form_row()
to add custom css around, then call form_widget()
to render the rest of the elements (another option would be form_rest()
)
What I am looking for is a way to check beforehand whether form_widget()
will print any objects or not, in order to add custom html in case there are extra fields.
The way I did it is like this:
//app/form/index.html.twig
{# Other template code #}
...
{# Rendering form: #}
{{ form_start(form) }}
{{ form_row(form.username) }}
{{ form_row(form.email) }}
{% set form_rendered = form_widget(form) %}
{% if form_rendered %}
<h3>Other fields</h3>
{{ form_rendered | raw }}
{% endif %}
{{ form_end(form) }}
{# End form #}
...
{# Other template code #}
However, I am not satisfied with it. Is there any better way?
Edit: When using CSRF Protection (activated by default), the previous code would ALWAYS print <h3>Other fields</h3>
, since the form has an extra hidden field for the token that we didn't print. We would need to render it somewhere with {{ form_row(form._token) }}
.