Symfony Render Form Elements By Hand without Losing CSRF

If you’re like me and you render your form widgets by hand with Symfony, read this.

I had a situation where at various places in my application I used a different number of form widgets of a particular form. Sometimes I used just a button, sometimes I used other widgets.

The problem I had to solve was that {{ form_end }} renders all of the previously non-rendered form widgets. That’s not what I want so I did this.

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

That “worked,” but it breaks Symfony’s built-in cross-site request forgery capability. Essentially the csrf hidden token element wasn’t being rendered. Fortunately, it was an easy fix, just render the csrf by hand like the other form widgets.

{{ form_widget(form._token) }}

Voila! Now csrf is working again.

Share Button