我在symfony2中有一个控制器,如下所示,如果用户表单有效,它将重定向到其他链接,但如果出现错误,它将保留在同一页面中并显示错误。当客户端验证被禁用并且只有服务器端验证在检查错误时,这只是一个简单的通用场景。
/**
* Creates a new User entity.
*
* @Route("/create", name="admin_user_create")
* @Method("post")
* @Template("UserBundle:User:new.html.twig")
*/
public function createAction()
{
$entity = new User();
$request = $this->getRequest();
$form = $this->createForm(new UserType() , $entity);
$form->bindRequest($request);
if($form->isValid())
{
// DO SOMETHING ...
return $this->redirect($this->generateUrl('some_link' , array( 'user_id' => $entity->getId() )));
}
// If the form is NOT valid, it will render the template and shows the errors.
return array(
'entity' => $entity ,
'form' => $form->createView()
);
}
场景如下:
- 用户为表单输入了一些无效数据
- 用户提交表单
- 控制器检查表单是否有效
由于它无效,它将呈现模板,在这种情况下为
@Template("UserBundle:User:new.html.twig")
- 浏览器中的路由将为
/create
- 如果浏览器链接上的用户
click
而不是post
将收到错误
我该怎么解决这个问题?我必须再次重定向吗?既然方法是post
,是否可以重定向?
不要指定@Method("POST")并在方法中执行此操作:
if ($request->getMethod() == 'POST')
{
$form->bindRequest($request);
if($form->isValid())
{
// DO SOMETHING ...
return $this->redirect($this->generateUrl('some_link' , array( 'user_id' => $entity->getId() )));
}
}
您可以接受GET
或POST
并执行某些链接:
/**
* Creates a new User entity.
*
* @Route("/create", name="admin_user_create")
* @Method("GET|POST")
* @Template("UserBundle:User:new.html.twig")
*/
public function createAction()
{
$entity = new User();
$request = $this->getRequest();
$form = $this->createForm(new UserType() , $entity);
// Is this POST? Bind the form...
if('POST' == $request->getMethod()) $form->bindRequest($request);
// GET or from not valid? Return the view...
if('GET' == $request->getMethod() || !$form->isValid()) :
return array(
'entity' => $entity ,
'form' => $form->createView()
);
endif;
// Success, then persist the entity and redirect the user
return $this->redirect($this->generateUrl('some_link',
array('user_id' => $entity->getId()))
);
}
/**
* Creates a new User entity.
*
* @Route("/create", name="admin_user_create")
* @Method("GET|POST")
* @Template("Use`enter code here`rBundle:User:new.html.twig")
*/
public function createAction()
{
$entity = new User();
$request = $this->getRequest();
$form = $this->createForm(new UserType() , $entity);
// Is this POST? Bind the form...
if('POST' == $request->getMethod()) $form->bindRequest($request);
// GET or from not valid? Return the view...
if('GET' == $request->getMethod() || !$form->isValid()) :
return array(
'entity' => $entity ,
'form' => $form->createView()
);
endif;
// Success, then persist the entity and redirect the user
return $this->redirect($this->generateUrl('some_link',
array('user_id' => $entity->getId()))
);
}