如果管理员添加注释,Symfony设置值1

时间:2017-09-28 05:29:35

标签: php symfony doctrine-orm symfony-2.8

我正在使用symfony 2.8,我在数据库的注释表中有状态字段,所以如果管理员在博客页面添加任何评论,它应该在数据库中保存为1状态。现在我正在保存showAction()方法的评论数据。

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

}

现在,如果普通用户添加任何评论,我已在Comment实体中定义了状态值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

1 个答案:

答案 0 :(得分: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));

}