FOSRestBundle - PATCH 无法正常工作

FOSRestBundle - PATCH not working as should

我想用 'PATCH' 方法更新实体(仅更新那些已提交的字段)。

  /* Edit an existing Content entity.
  *
  * @Rest\Patch(
  *     "/{content}.{_format}",
  *     requirements={"content" = "\d+"},
  *     defaults = { "_format" = "json" }
  * )
  *
  * @Rest\View(serializerGroups={"user""admin"})
  * @param Content $content
  * @return View
  * @throws \NotFoundHttpException*
  *
  * @ApiDoc(
  *  resource="/api/content/",
  *  description="Updates content data",
  *
  *  input="ContentBundle\Form\ContentType",
  *
  *  output={
  *   "class"="EntriesBundle\Entity\Content",
  *   "parsers"={"Nelmio\ApiDocBundle\Parser\JmsMetadataParser"},
  *   "groups"={"user","admin"}
  *  }
  * )
  */
 public function editAction(Request $request, Content $content)
 {
     if (!$content) {
         throw $this-createNotFoundException();
     }

     $editForm = $this-createForm('ContentBundle\Form\ContentType', $content);
     $editForm-submit($request-request-get($editForm-getName()));

     $view = View::create()
         -setSerializationContext(SerializationContext::create()-setGroups(['user']));

     if ($editForm-isSubmitted() && $editForm-isValid()) {
         $em = $this-getDoctrine()-getManager();
         $em-persist($content);
         $em-flush();

         $view
             -setStatusCode(Codes::HTTP_OK)
             -setTemplate("ContentBundle:content:show.html.twig")
             -setTemplateVar('contents')
             -setData($content);

     } else {
         $view
             -setStatusCode(Codes::HTTP_BAD_REQUEST)
             -setTemplateVar('error')
             -setData($editForm)
             -setTemplateData(['message' = $editForm-getErrors(true)])
             -setTemplate('ContentBundle:content:show.html.twig');
     }

     return $this-get('fos_rest.view_handler')-handle($view);
 }

表格:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title', TextType::class)
        ->add('description', TextareaType::class)
        ->add('eng', CheckboxType::class, [
            'required' => false
        ]);
}

我的实体 'eng' 设置为 TRUE。 如果我 运行 查询仅更新 title 字段,eng 将更改为 false。和 description 为空。有什么想法吗?

我认为,因为您没有使用请求主体转换器,而是手动定义路由,所以需要设置表单的方法。

尝试这样的事情:

$editForm = $this->createForm(
   'ContentBundle\Form\ContentType', 
   $content, 
   ['method' => 'PATCH']
);

我已经开始工作了。

请记住,如果您想使用 PATCH 方法,您需要在表单中使用 TextType 而不是 ChoiceType

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class)
            ->add('description', TextareaType::class)
            ->add('eng', TextType::class);
    }