21

Okay, so today I updated my database with new information from our 'live' database... And since then I've been having issues on one of my forms. If you need any code let me know and i'll edit this and post the code needed...

I have a report form which has a date range field and a drop down for an agent department. When I first visit the page I see this at the beginning of the form:

The CSRF token is invalid. Please try to resubmit the form

So I go over to one of my other forms that has the same type of information, and check the _token out and this is what comes out:

<input type="hidden" id="ecs_crmbundle_TimeClockReportType__token" name="ecs_crmbundle_TimeClockReportType[_token]" value="87e358fbc4d6d3e83601216b907a02170f7bcd92" />
<input type="hidden" id="ecs_crmbundle_SimpleSalesReportType__token" name="ecs_crmbundle_SimpleSalesReportType[_token]" value="87e358fbc4d6d3e83601216b907a02170f7bcd92" />

The first one is the one that shows the error, and the SimpleSalesReport does not... Any idea why this is doing this or how I can fix it?

Thanks..

Justin
  • 2,131
  • 4
  • 24
  • 41

3 Answers3

26

Are you by chance using $form->bindRequest() in the action which produces the CSRF error? I had this issue. You should not be binding the request for a new form. If you are posting the form to the same action, wrap the bindRequest in a conditional which checks if method is POST:

if ($this->getRequest()->getMethod() == 'POST') {
  $form->bindRequest($this->getRequest());
  if ($form->isValid()) {
    ...
  }
}
dylan oliver
  • 1,274
  • 9
  • 16
  • 3
    the man is a freakin genius! That's EXACTLY what I was doing... But you have come and saved the day! – Justin May 14 '12 at 23:24
  • 22
    Also, remember to add form_rest(form) at the bottom, as the last field in the form. Symfony takes cares of inserting CSRF token for you with that statement. http://symfony.com/doc/current/book/forms.html#rendering-a-form-in-a-template – krishna May 29 '12 at 14:52
  • @krishna That's exactly what I was missing; sloppy copy/paste on my part! – OrganicPanda Aug 31 '12 at 08:52
  • You are great! Thanks for solving my problem, too. – Faery Sep 13 '12 at 08:22
  • 2
    Can also use `$this->getRequest()->isMethod('POST')`. – Sam Selikoff Mar 11 '13 at 23:38
  • krishna's comment saved me the night. I did not put `form_rest(form)` because I already had all my fields, while symfony adds some hidden control fields (for example an ``). – Xavi Montero Apr 16 '13 at 01:47
22

There is no problem using {{ form_widget(form) }} to build your custom form. All you have to do is add the _token like this: {{ form_widget(form._token) }}

Florent
  • 12,310
  • 10
  • 49
  • 58
Marc Juchli
  • 2,240
  • 24
  • 20
18

This error had me crazy for days! Thanks krishna! If in your form template you choose to not use the default form behavior {{ form_widget(form) }} you SHOULD put {{ form_rest(form) }} Hope this could help anyone else!

MatuDuke
  • 4,997
  • 1
  • 21
  • 26