使用FosRestBundle的主体转换器编辑对象

时间:2017-08-06 17:45:15

标签: rest symfony fosrestbundle

我使用symfony3和FosRestBundle作为后端。要创建对象,我使用没有FormType的Fosrestbundle的正文转换器 fos_rest.request_body

但是,当我使用 body转换器编辑对象时,它不起作用,没有错误,但数据库中没有任何更改。

/**
 * @Rest\Put(
 *    path = "/comments/update/{id}",
 *    name = "app_comment_edit"
 * )
 * @Rest\View(StatusCode = 200, serializerGroups={"edit"})
 * @ParamConverter("comment", converter="fos_rest.request_body")
 */
public function updateAction(Request $request, Comment $comment,$id,  ConstraintViolationList $violations)
{
    $em = $this->getDoctrine()->getManager();
    $comment = $em->getRepository('AppBundle:Comment')->find($id);

    if (count($violations)) {
        return $this->view($violations, Response::HTTP_BAD_REQUEST);
    }

    $em->flush();

    return $comment;
}

要进行更改,我必须使用$ request:

    $comment->setEmail($request->request->get('email'));
    $comment->setContent($request->request->get('content'));
    $em->flush();

我的问题是,FosUserBundle的正文转换器在编辑对象时不起作用,我必须使用上面的方法或使用FormType?

1 个答案:

答案 0 :(得分:0)

你必须在保存对象之前打电话:

******
$em->persist($comment);
$em->flush();

例如:

https://symfony.com/doc/current/doctrine.html#persisting-objects-to-the-database