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?
Sure, it's possible.
First, in terms of RESTful that would be a
PATCH
request, so if you're using theClassResourceInterface
based controller approach, you'll have to add apatchAction
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: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 aFormInterface::submit()
method will be deprecated as of Symfony 3.0, so this answer is for Symfony 2.x.