Symfony2 REST API - Partial update

2019-07-21 03:44发布

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条回答
何必那么认真
2楼-- · 2019-07-21 03:56

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.

查看更多
登录 后发表回答