Answer the question
In order to leave comments, you need to log in
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);
Answer the question
In order to leave comments, you need to log in
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);
}
}
/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 questionAsk a Question
731 491 924 answers to any question