Symfony2表单提交页面刷新

时间:2013-04-26 06:27:15

标签: php symfony form-submit symfony-forms 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文件,其中包含上面提到的参数和警报消息。但我不希望在页面刷新时提交表单。

由于

3 个答案:

答案 0 :(得分:4)

This worked for me:

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

答案 1 :(得分:3)

您应该在会话中保存提交的数据并重定向用户。然后,您可以根据需要刷新页面而无需额外提交。 示例代码 - 您的操作算法应该类似:

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

重定向到同一页面阻止了其他数据提交。这个例子很精简修改你的动作,你会没事的。 而是在会话中保存数据,您可以通过重定向请求传递它。但我认为这种方法更难。

答案 2 :(得分:1)

  1. 保存您的数据(会话/数据库/您希望保存的地方)
  2. 重定向到新操作,在该操作中检索新数据,然后呈现模板
  3. 通过这种方式刷新新操作,只会刷新模板,因为在上一个操作中保存了您的数据

    明白了吗?

    所以基本上替换你的

    return $this->render....
    

    通过

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

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

    return $this->render....
    
相关问题