“The CSRF token is invalid” error in symfony 2 even using form_rest(form) function

匿名 (未验证) 提交于 2019-12-03 09:06:55

问题:

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!