Alfro Alfro - 4 months ago 18
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

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) }}
.

Answer

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

//src/Symfony/Component/Form/FormView.php

    /**                                                                  
     * 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 %}