I've been trying to create a simple form in symfony but each time I try to submit I get the following error:
ERROR: The CSRF token is invalid. Please try to resubmit the form.
After surfing on the Internet and reducing the code to almost empty. I still get that error. Most of the people who I've seen asking for that solved the error using the following twig code
{{ form_rest(form) }}
The problem is that I'm using it, it's like when I bind the request it doesn't do it correctly. I don't know what else can I do.
This is my small twig template:
<div><h2>Insert new activity</h2></div> <div> <form id="new-activity" action="{{ path('create') }}" method="post" {{ form_enctype(form) }}> {{ form_rest(form) }} <p> <button type="submit">Submit</button> </p> </form> </div>
As you can see it is pretty small code. This is my form render code:
/** * Displays a form to create a new Activity entity. * * @Route("/new", name="sucr_new") * @Template() */ public function newAction() { $initialConfig = new SucrConfiguration(); $finalConfig = new SucrConfiguration(); $activity = new SucrActivity(); $data = array("activity" =>$activity, "initialConfig" => $initialConfig, "finalConfig" => $finalConfig); $form = $this->createForm(new ActivityType(), $data); return array( 'data' => $data, 'form' => $form->createView() ); }
And this is the code that should handle the submition:
/** * Displays a form to create a new Activity entity. * * @Route("/create", name="create") * @Method("post") * @Template("EusocSucrBundle:Sucr:new.html.twig") */ public function createAction() { $initialConfig = new SucrConfiguration(); $finalConfig = new SucrConfiguration(); $activity = new SucrActivity(); $data = array("activity" =>$activity, "initialConfig" => $initialConfig, "finalConfig" => $finalConfig); $form = $this->createForm(new ActivityType(), $data); if ($this->getRequest()->getMethod() == 'POST') { $form->bindRequest($this->getRequest()); if ($form->isValid()) { return $this->redirect($this->generateUrl('sucr_show', array('id' => 1))); } var_dump($form->getErrorsAsString()); } return array( 'data' => $data, 'form' => $form->createView() ); }
Also note that I can see the hidden token in my browser.
Any ideas?