persist new entity onFlush
doctrine, doctrine-orm, php
Solution
I had similar issues with onFlush Event. Please change
$em->persist($notification);
to
$uow = $em->getUnitOfWork();
$uow->persist($notification);
$metadata = $em->getClassMetadata(get_class($notification));
$uow->computeChangeSet($metadata, $notification);
`$uow->persist()` will make the UnitOfWork know about the new entity and will schedule it for insertion. Calling `$uow->computeChangeSet()` is neccessary, to collect the data that should be inserted by Doctrine's persister.
Problem
I try to user the `onFlush` Event in Doctrine to persist a new entity, but it leads to an infinite loop when trying to persist. Here is what I do in the Listener: ``` $countusers = $em->getRepository('DankeForumBundle:NotificationUser')->countNotificationsByDeal($entity); if ($countusers > 0) { $notification = new NotificationAction(); $notification->setDeal($entity); $notification->setDatepost(new \DateTime()); $notification->setNotificationtype(NotificationAction::TYPE_TOP_DEAL); // $em is set to EntityManager $em->persist($notification); // $uow ist set to UnitOfWork $uow->computeChangeSet($em->getClassmetadata('Danke\ForumBundle\Entity\NotificationAction'), $notification); } ``` I know that I would get a loop, when I was flushing in the `onFlush` Event, but I don't do that! I only compute the new change set as it says in the documentation. Can someone tell where the problem is?