dsf8897 2014-02-25 17:03
浏览 35

即使使用form_rest(form)函数,symfony 2中的“CSRF令牌无效”错误

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?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 怀疑手机被监控,请问怎么解决和防止
    • ¥15 Qt下使用tcp获取数据的详细操作
    • ¥15 idea右下角设置编码是灰色的
    • ¥15 全志H618ROM新增分区
    • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
    • ¥15 NAO机器人的录音程序保存问题
    • ¥15 C#读写EXCEL文件,不同编译
    • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
    • ¥15 扩散模型sd.webui使用时报错“Nonetype”
    • ¥15 stm32流水灯+呼吸灯+外部中断按键