1

我有一个表单,它必须通过一些其他验证而不是不寻常的(大约 4 个字段相互依赖)。事情是,当它失败时,我将用户重定向回来,但随后表单丢失了它的值,我不想要它。我知道它可以通过会话来完成,但可能有一种“更健康”的方式。代码很常见:

public function printAction()
{
    if ($this->getRequest()->getMethod() == "POST")
    {
        $form->bindRequest($this->getRequest());
        if ($form->isValid())
        {
             .... more validation.... Failed!
             return $this->redirect($this->generateUrl("SiteHomePeltexStockStockHistory_print"));
             // and this is when I lose the values.... I dont want it
        }
    }
}
4

3 回答 3

2

您可以对与表单相关的请求GET和请求使用相同的操作。POST如果验证失败,请不要重定向,相同的表单将重新显示输入值和验证错误消息:

/**
 * @Template
 */
public function addAction(Request $request)
{
    $form = /* ... */;        

    if ($request->isMethod('POST')) {
        $form->bind($request);

        if ($form->isValid()) {
            // do something and redirect
        }

        // the form is not valid, so do nothing and the form will be redisplayed
    }

    return [
        'form' => $form->createView(),
    ];
}
于 2013-04-08T09:04:22.980 回答
1

进行新重定向时,您可以将参数传递到新页面:

$this->redirect($this->generateUrl('SiteHomePeltexStockStockHistory_print', array('name1' => 'input1', 'name2' => 'input2', 'name3' => $input3, ....)));

或直接传递一个 post 值数组:

$this->redirect($this->generateUrl('SiteHomePeltexStockStockHistory_print', array('values' => $values_array)));
于 2013-04-08T09:05:17.590 回答
1

你可能想做这样的事情

class FooController extends Controller
{
    /**
     * @Route("/new")
     * @Method({"GET"})
     */
    public function newAction()
    {
        // This view would send the form content to /create
        return $this->render('YourBundle:form:create.html.twig', array('form' => $form));
    }

    /**
     * @Route("/create")
     * @Method({"POST"})
     */
    public function createAction(Request $request)
    {
        // ... Code
        if ($form->isValid()) {
            if (/* Still valid */) {
                // Whatever you do when validation passed
            }
        }

        // Validation failed, just pass the form
        return $this->render('YourBundle:form:create.html.twig', array('form' => $form));
    }
}
于 2013-04-08T09:08:37.590 回答