I am trying to serialize and then deserialize a Doctrine Entity in Symfony 3. Well it does not work for the id property of course because there's no public accessor to the id by default. So what's the best option for that?
Add a setId() method, but that's probably a bad idea and
undermines the doctrine default behaviour.
Use a custom Normalizer that uses reflection to construct the
object by just accessing the field.
Give the entity some custom toArray(), fromArray() functionality and use the array values instead of the object in the serialization.
Or am i missing something? Is there already something build into symfony for that usecase?
You can use object_to_populate option to do that :
// retrieve entity to update from DB
$oldProduct = $this->getDoctrine()->getRepository(Product::class)->find($request->request->get('id'));
$product = $this->get('serializer')->deserialize($request->getContent(), Product::class, 'json', array('object_to_populate' => $oldProduct));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($product);
$entityManager->flush();