I'm using symfony 2.8, I have status field in the comment table in database, so If admin add any comment from blog page, it should be saved 1 as status in the db. Now I'm saving comment data from showAction() method.
showAction() method
public function showAction(Request $request,$id)
{
$blog = $this->getDoctrine()->getRepository(Blog::class)->findOneById($id);
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user = new User();
$comment->setUser($this->getUser());
$comment->setBlog($blog);
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
$comment->setstatus(1);
}
$em = $this->getDoctrine()->getManager();
$em->merge($comment);
$em->flush();
return $this->redirect($this->generateUrl('blog_show', array('id' => $id)), 301);
//return $this->redirectToRoute('blog_list');
}
$comments = $blog->getComment($comment);
return $this->render('Blog/show.html.twig', array('blog'=> $blog,'form' => $form->createView(),'comments'=>$comments));
}
Now if normal user add any comment, I have defined value 0 of status in Comment entity, so that it is automatically insert 0(PrePersist).
Comment Entity
/**
* @ORM\PrePersist
*/
public function setStatusValue() {
$this->status = 0;
}
/**
* Set status
*
* @param int $status
* @return status
*/
public function setstatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return status
*/
public function getStatus()
{
return $this->status;
}
Now what I want is as per my showAction() method, I want the status 1 in comment table when Admin add any comment. Its storing 0 in both normal and admin user case. Any help is much appreciated.
More code is available at this question.. Symfony Save comments on blog with user and blogId
I solved this problem by removing setStatusValue() (Prepersist method) from comment entity and adding status from controller for both normal and admin user.
showAction() method
public function showAction(Request $request,$id)
{
$blog = $this->getDoctrine()->getRepository(Blog::class)->findOneById($id);
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user = new User();
$comment->setUser($this->getUser());
$comment->setBlog($blog);
$comment->setstatus(0);
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
$comment->setstatus(1);
}
$em = $this->getDoctrine()->getManager();
$em->merge($comment);
$em->flush();
return $this->redirect($this->generateUrl('blog_show', array('id' => $id)), 301);
}
$comments = $blog->getComment($comment);
return $this->render('Blog/show.html.twig', array('blog'=> $blog,'form' => $form->createView(),'comments'=>$comments));
}