Alfro Alfro - 1 year ago 173
Twig Question

How can I detect if a form has any elements left to be rendered?

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

to add custom css around, then call
to render the rest of the elements (another option would be
What I am looking for is a way to check beforehand whether
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:

{# Other template code #}
{# Rendering form: #}
{{ form_start(form) }}

{{ form_row(form.username) }}
{{ form_row( }}

{% 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) }}

Answer Source

By checking the code in src/Symfony/Component/Form/FormView.php, I found a function that does exactly what I wanted.


     * Returns whether the view was already rendered. 
     * @return bool Whether this view's widget is rendered 
     public function isRendered()
        $hasChildren = 0 < count($this->children);

        if (true === $this->rendered || !$hasChildren) {
            return $this->rendered;

        if ($hasChildren) {
            foreach ($this->children as $child) {
                if (!$child->isRendered()) {
                    return false;

            return $this->rendered = true;

        return false;

Now the function can be used in the template as such:

{% if not form.isRendered() %}
    <h3>Other fields</h3>
    {{ form_widget(form) }}
{% endif %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download