Masha Masha - 5 months ago 27
PHP Question

Symfony2 and Twig form rendering in if - else condition

In my Symfony 2 app I got the following code rendering the form:

{{ form_start(form) }}
{{ form_errors(form) }}
<div class="form-group">
{{ form_label(form.title) }}
{{ form_widget(form.title) }}
<div class="form-group">
{{ form_label(form.message) }}
{{ form_widget(form.message) }}
{% if extras == true %} //this block should be rendered only if extras var is true
<div class="form-group">
{{ form_label(form.description) }}
{{ form_widget(form.description) }}
{% endif %}
{{ form_end(form) }}

The problem is that I get rendered {{ form_widget(form.description) }} even if my extras var is false, not with all other form fields but somewhere at the bottom of the form which is obviously a bug. How to make it render only if extras is true and disappear completely from the page in case extras is false?
Thank you.


All other form fields are automatically added to the end of your form by default. It triggers {{ form_rest() }} by default. Use this code to prevent this behavior:

{{ form_end(form, {'render_rest': false}) }}