I have an onFlush () event that works fine, but I need to do this to turn this into preFlush () or preUpdate () as acceptable. I did preFlush (), but for some reason does nothing. Even a mistake. What am I missing?
TEST: I placed exit in preFlush() to see if it would be called at all or not. Result: 1 , so foreach() never starts! This is an empty array. I also tested preUpdate () and all the lines in which data is started but not inserted.
public function preFlush(PreFlushEventArgs $args) { $em = $args->getEntityManager(); $uow = $em->getUnitOfWork(); echo '1'; foreach ($uow->getScheduledEntityUpdates() as $entity) { echo '2'; if ($entity instanceof User) { echo '3'; } } exit; }
I created them after reading the documentation .
service.yml
services: entity.event_listener.user: class: Site\FrontBundle\EventListener\Entity\UserListener tags: - { name: doctrine.event_listener, event: preUpdate } - { name: doctrine.event_listener, event: onFlush } - { name: doctrine.event_listener, event: preFlush }
Working example onFlush ():
class UserListener { public function onFlush(OnFlushEventArgs $args) { $em = $args->getEntityManager(); $uow = $em->getUnitOfWork(); foreach ($uow->getScheduledEntityUpdates() as $entity) { if ($entity instanceof User) { $userLog = new UserLog(); $userLog->setDescription($entity->getId() . ' being updated.'); $em->persist($userLog);
The preFlush () example does not work:
class UserListener { public function preFlush(PreFlushEventArgs $args) { $em = $args->getEntityManager(); $uow = $em->getUnitOfWork(); foreach ($uow->getScheduledEntityUpdates() as $entity) { if ($entity instanceof User) { $userLog = new UserLog(); $userLog->setDescription($entity->getId() . ' being updated.'); $em->persist($userLog);
The preUpdate () example does not work
class UserListener { public function preUpdate(LifecycleEventArgs $args) { $entity = $args->getEntity(); $em = $args->getEntityManager(); $uow = $em->getUnitOfWork(); if ($entity instanceof User) { $userLog = new UserLog(); $userLog->setDescription($entity->getId() . ') been updated.'); $em = $args->getEntityManager(); $em->persist($userLog); $userLogMetadata = $em->getClassMetadata(get_class($userLog)); $uow->computeChangeSet($userLogMetadata, $userLog); } } }