我有一个表单,必须通过一些其他验证而不是异常(大约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
}
}
}
答案 0 :(得分: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(),
];
}
答案 1 :(得分:1)
在进行新的重定向时,您可以将参数传递到新页面:
$this->redirect($this->generateUrl('SiteHomePeltexStockStockHistory_print', array('name1' => 'input1', 'name2' => 'input2', 'name3' => $input3, ....)));
或直接传递一系列帖子值:
$this->redirect($this->generateUrl('SiteHomePeltexStockStockHistory_print', array('values' => $values_array)));
答案 2 :(得分: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));
}
}