我一直在尝试在symfony中创建一个简单的表单,但每次我尝试提交时都会出现以下错误:
ERROR: The CSRF token is invalid. Please try to resubmit the form.
在互联网上冲浪并将代码减少到几乎为空。我仍然得到那个错误。我见过要求的大多数人使用以下树枝代码解决了错误
{{ form_rest(form) }}
问题是我正在使用它,就像我绑定请求时它没有正确使用它。我不知道还能做些什么。
这是我的小树枝模板:
<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>
正如您所看到的,它是非常小的代码。这是我的表单呈现代码:
/**
* 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()
);
}
这是应该处理子目录的代码:
/**
* 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()
);
}
另请注意,我可以在浏览器中看到隐藏的令牌。
有什么想法吗?