[英]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.