2013-04-26 177 views
2

我在Symfony2框架中有一个表单。成功提交页面时,它呈现另一个树枝模板文件,并通过传递数组中的参数来返回值。但提交后,如果我刷新页面,它又提交表单并创建表格条目。这里是提交在控制器后执行的代码,Symfony2表单提交页面刷新

$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, 
      )); 

我想要的形式被重定向到的参数与上面提到的警告消息中提到那里的树枝文件。但我不希望表单在页面刷新时提交。

感谢

回答

2

您应该保存提交的数据会话和重定向用户。然后,您可以根据需要尽可能多地刷新页面,而无需额外提交。 示例代码 - 你的行动的算法应该是相似的:

... 
/** 
* @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() 
)); 
} 

重定向到同一个页面是防止更多的数据提交。所以这个例子的精益修改你的行为,你会没事的。 而是保存会话中的数据,您可以通过重定向请求传递它。但我认为这种方法更加困难。

0
  1. 保存数据(会话/ DB /无论你想它保存)
  2. 重定向到一个新的行动,在行动以便在检索新数据,并绘制模板

这样,刷新新动作,只刷新模板,因为保存你的数据发生在前面的动作

明白吗?

所以基本上取代你

return $this->render.... 

通过

return $this->redirect($this->generateUrl('ROUTE_TO_NEW_ACTION'))); 

,并在这个新的动作,你把你的

return $this->render.... 
3

这为我工作:

return $this->redirectToRoute("route_name"); 
+0

工程就像一个魅力! – Keutelvocht 2017-09-05 10:58:35