我在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
,是否可以重定向?
答案 0 :(得分:2)
不要指定@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() )));
}
}
答案 1 :(得分:0)
您可以接受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()))
);
}
答案 2 :(得分:0)
/**
* 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()))
);
}