doujuegai8830 2014-09-03 07:39
浏览 73
已采纳

Symfony2 REST API - 部分更新

I'm building a REST API with FOSRestBundle in Symfony2. I'm using forms to create and update entities with Doctrine2. Everything works fine if I send all form fields. Example:

{"first_name":"Pi","last_name":"Wi"}

The person is inserted fine but now I want to update only the last name.

{"last_name":"Wi"}

The problem is that the first name is empty after the update because the form updates the entity with an "null" value (because it isn't given). Is it possible to just update the last name and ignore the first name?

  • 写回答

1条回答 默认 最新

  • dongyuan8024 2014-09-03 07:49
    关注

    Sure, it's possible.

    First, in terms of RESTful that would be a PATCH request, so if you're using the ClassResourceInterface based controller approach, you'll have to add a patchAction method in your controller.

    Then, when processing a submitted form, you'll need to pass a false $clearMissing option to your form's submit method call in the controller, like this:

    <?php
    // in your controller's patchAction:
    
    /** @var \Symfony\Component\Form\FormInterface $form  */
    /** @var \Symfony\Component\HttpFoundation\Request $request */
    
    $form->submit($request, false);
    

    This will tell the form component to only update the fields passed from the form, without clearing the missing fields (as the parameter's name says). See the source code for reference.

    Note though, that passing a Request to a FormInterface::submit() method will be deprecated as of Symfony 3.0, so this answer is for Symfony 2.x.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)