好的我卡住了,没有关于此的文档信息(如果我错了,请纠正我)
示例:我在控制器中有更新metod,某种形式,如果forim有效,我使用flush方法进行更改。我如何检查是否在数据库中进行了更改,以便我可以发送Flash消息,如果更改已成功“成功”或如果有错误则执行查询我发送闪存消息“无法更改数据库”
这是我的代码的示例,但我认为flush返回void或null所以这不是要走的路,也许它会在失败时返回一些例外我不知道..
/**
* @Route("createpost", name="createpost")
*/
public function createPostAction(Request $request) {
if (!$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
throw $this->createAccessDeniedException();
}
$post = new Post();
$form = $this->createForm(new PostForm(), $post);
$form->handleRequest($request);
if($form->isValid()) {
$user = $this->getUser();
$author = $user->getUsername();
//$post->setPublishDate(new \DateTime);
$post->setAuthor($author);
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$pom = $em->flush();
return $this->render('success/success.html.twig', array(
'test' => var_dump($pom)
));
if($pom) {
$this->addFlash(
'notice',
'You have successfully created post'
);
}
return $this->redirectToRoute('home', array(), 301);
}
return $this->render(
'create/post.html.twig', array(
'form' => $form->createView()
));
}
答案 0 :(得分:3)
你可以这样做:
String
但是,您不需要检查flush是否正常工作,如果出现问题则会抛出异常..
评论更新:
...
if($form->isValid()) {
$user = $this->getUser();
$author = $user->getUsername();
//$post->setPublishDate(new \DateTime);
$post->setAuthor($author);
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
if(null != $post->getId()) {
$this->addFlash(
'notice',
'You have successfully created post'
);
return $this->render('success/success.html.twig', array(
'test' => var_dump($pom)
));
}
// This line never be called
return $this->redirectToRoute('home', array(), 301);
}
...
答案 1 :(得分:0)
更改
return $this->render('success/success.html.twig', array(
'test' => var_dump($pom)
));
if($pom) {
$this->addFlash(
'notice',
'You have successfully created post'
);
}
要
if($pom) {
$this->addFlash(
'notice',
'You have successfully created post'
);
}
return $this->render('success/success.html.twig', array(
'test' => var_dump($pom)
));
您需要在返回响应之前添加闪存