Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 REST API - Partial update

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?

like image 554
Pi Wi Avatar asked Oct 21 '25 23:10

Pi Wi


1 Answers

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.

like image 139
kix Avatar answered Oct 23 '25 13:10

kix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!