F
F
fman22020-11-09 16:43:00
symfony
fman2, 2020-11-09 16:43:00

How to tell the EntityManager about an entity?

Hello.
I have a Comment entity that is filled with data from an array via symfony/serializer, and this data comes from the form accordingly. Yes, there is no symfony on the project, the project is old, I am moving it to components.

The entity has an $id which is the primary key. Accordingly, when editing a comment, its setId method is called:

$serializer->denormalize($request->request->all(), Comment::class);


But EM doesn't know anything about this entity and when persist()/flush() it creates a new entity, ignoring the identifier. How to make it so that the data is filled from the serializer and at the same time the doctrine does not ignore $id?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2020-11-09
@fman2

https://symfony.com/doc/current/components/seriali...
This can be wrapped in some custom normalizer

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

class MyObjectDenormalizer implements DenormalizerInterface
{
    private ObjectNormalizer $objectNormalizer;
    private EntityManagerInterface $entityManager;

    public function __construct(ObjectNormalizer $objectNormalizer, EntityManagerInterface $entityManager)
    {
        $this->objectNormalizer = $objectNormalizer;
        $this->entityManager = $entityManager;
    }

    public function denormalize($data, string $type, string $format = null, array $context = [])
    {
        if ($id = $data['id'] ?? null) {
            $object = $this->entityManager->getRepository($type)->find($id);
            $context = [
                AbstractObjectNormalizer::OBJECT_TO_POPULATE => $object,
            ];
            unset($data['id']);
        }

        return $this->objectNormalizer->denormalize($data, $type, $format, $context);
    }

    public function supportsDenormalization($data, string $type, string $format = null)
    {
        return $this->objectNormalizer->supportsDenormalization($data, $type, $format);
    }
}

But it's better to substitute the object in the controller based on the data from the route ( /comment/{id}/edit), because it is possible to change the id and edit another entity (to which, for example, the user does not have access)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question