While ago I have asked same question Symfony PUT does not contain all entity properties mapped and I've got some #hack solution to solve the problem but when the form is more complex, contains choices (arrays) or mapped entities (objects) the solution is not applicable anymore. So I came up with very dirty ideas to make it work such as
if(is_object($event->getForm()->getData())) $event->setData($event->getForm()->getData()->getId());
if(is_array($event->getData()) && empty($event->getData()))
{
$event->setData([$event->getForm()->getData()]);
}
if($event->getForm()->getData() instanceof \DateTime) $event->setData($event->getForm()->getData()->format('Y-m-d H:i:s'));
if(!is_array($event->getData()) && (is_string($event->getForm()->getData()) || is_integer($event->getForm()->getData())))
{
$event->setData($event->getForm()->getData());
}
but it's not even working perfect. So I must ask one more time if there's a better solution to updatejust one value at the time of sending json response, because if I send {"user":{"firstName":"John"}}
all other fields belonging to the User form are empty and I cannot send entire resource. I cannot find any solution to this problem.
And here's the Controller
/**
* This endpoint updates an existing Client entity.
*
* @ApiDoc(
* resource=true,
* description="Updates an existing Client entity",
* )
* @ParamConverter("user", class="Software:User", options={"mapping": {"user": "guid"}})
*/
public function putAction(Request $request, $user)
{
$form = $this->createForm(new UserType(['userType' => 'client', 'manager' => $this->getDoctrine()->getManager()]), $user, ['method' => 'PUT']);
$form->handleRequest($request);
if($form->isValid())
{
$manager = $this->getDoctrine()->getManager();
$manager->flush();
return $this->view([
'user' => $user
]);
}
return $this->view($form);
}
I am going to answer my own question.
The answer is to use
PATCH
method instead of PUT. Here's the modified code:Please find references: Symfony2 REST API - Partial update
http://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/
http://williamdurand.fr/2014/02/14/please-do-not-patch-like-an-idiot/
Read carefully PATCH vs. PUT chapters.