[英]Symfony2 form submitting on page refresh
我在Symfony2框架中有一个表单。 成功提交页面后,它会呈现另一个twig模板文件,并通过在数组中传递参数来返回值。 但提交后,如果我刷新页面,则再次提交表单并创建表条目。 这是在控制器中提交后执行的代码,
$this->get('session')->setFlash('info', $this->get('translator')->trans('flash.marca'));
return $this->render('NewBundle:Backend:marca.html.twig', array(
'active' => 1,
'marca' => $marca,
'data' => $dataCamp,
'dataMarca' => $this->getMarcas($admin->getId()),
'admin' => $admin,
));
我希望通过上面提到的参数和警报消息将表单重定向到那里提到的twig文件。 但我不希望在页面刷新时提交表单。
谢谢
这对我有用:
return $this->redirectToRoute("route_name");
您应该在会话中保存提交的数据并重定向用户。 然后,您可以根据需要刷新页面而无需额外提交。 示例代码 - 您的操作算法应该类似:
...
/**
* @Route("/add" , name="acme_app_entity_add")
*/
public function addAction()
{
$entity = new Entity();
$form = $this->createForm(new EntityType(), $entity);
$session = $this->get('session');
// Check if data already was submitted and validated
if ($session->has('submittedData')) {
$submittedData = $session->get('submittedData');
// There you can remove saved data from session or not and leave it for addition request like save entity in DB
// $session->remove('submittedData');
// There your second template
return $this->render('AcmeAppBundle:Entity:preview.html.twig', array(
'submittedData' => $submittedData
// other data which you need in this template
));
}
if ($request->isMethod('POST')) {
$form->bindRequest($request);
if ($form->isValid()) {
$this->get('session')->setFlash('success', 'Provided data is valid.');
// Data is valid so save it in session for another request
$session->set('submittedData', $form->getData()); // in this point may be you need serialize saved data, depends of your requirements
// Redirect user to this action again
return $this->redirect($this->generateUrl('acme_app_entity_add'));
} else {
// provide form errors in session storage
$this->get('session')->setFlash('error', $form->getErrorsAsString());
}
}
return $this->render('AcmeAppBundle:Entity:add.html.twig', array(
'form' => $form->createView()
));
}
重定向到同一页面会阻止其他数据提交。 这个例子很精简修改你的动作,你会没事的。 而是在会话中保存数据,您可以通过重定向请求传递它。 但我认为这种方法更难。
这样,刷新新操作,只会刷新模板,因为在上一个操作中保存了您的数据
懂吗?
所以基本上替换你的
return $this->render....
通过
return $this->redirect($this->generateUrl('ROUTE_TO_NEW_ACTION')));
在这个新动作中,你把你的
return $this->render....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.