2017-09-28 96 views
0

我使用symfony 2.8,我在數據庫的註釋表中有狀態字段,所以如果管理員從博客頁面添加任何評論,它應該被保存爲1作爲db狀態。現在我正在保存來自showAction()方法的評論數據。Symfony設置值1如果管理員添加評論

的showAction()方法

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)); 

} 

現在,如果普通用戶添加任何評論,我已經定義的在評論實體狀態值0,以便它自動插入0(PrePersist)。

評論實體

/** 
* @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; 
} 

現在,我要的是按我的showAction()方法,我想在評語表1的狀態時,管理員添加任何評論。它在正常和管理用戶情況下都存儲0。任何幫助深表感謝。

更多代碼可在這個問題.. Symfony Save comments on blog with user and blogId

+0

如果你對新增評論路線來管理的防火牆下,那麼你可以檢查'isGranted'部分否則將始終返回false和奶嘴它作爲一個普通用戶 –

+0

這是檢查是否符合要求。我已經檢查過了。 – Aamir

+0

請參閱dump($ comment)輸出,如果條件在這裏,我已經在下面添加了isGranted。 http://mysticpaste.com/9STKB8DzpY – Aamir

回答

0

我通過從評論實體去除setStatusValue()(Prepersist法)和從控制器添加狀態爲正常和管理員用戶解決了這個問題。

的showAction()方法

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)); 

}