Symfony2 REST API - Partial update

China☆狼群 提交于 2019-12-11 02:04:26

问题


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:


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.



来源:https://stackoverflow.com/questions/25638813/symfony2-rest-api-partial-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!