0

Within a given lifecycle callback, can another object be modified and added to the same flush? Originally, I didn't include a second flush() in the callback and it wasn't being saved. I try adding one and it is saved but initiates multiple calls to EntityOne::preFlush() and I needed to add a flag to ignore the future calls which doesn't seem right. What is the correct way to do this?

<?php
class MyService
{
    public function save()
    {
        //...
        $this->em->persist($entityTwo);
        $this->em->flush();      
    }
}

class EntityOne
{
    /**
    * @var EntityTwo
    */
    private $entityTwo;

    private $preFlushComplete=false;

    /**
    * @ORM\PreFlush
    */
    public function preFlush(PreFlushEventArgs $event)
    {
        if(!$this->preFlushComplete) {
            $this->preFlushComplete=true;
            $this->entityTwo->setTime(now());
            $event->getEntityManager()->persist($this->entityTwo);
        }
    }
}
user1032531
  • 24,767
  • 68
  • 217
  • 387
  • Does this answer your question? [Persisting other entities inside preUpdate of Doctrine Entity Listener](https://stackoverflow.com/questions/30734814/persisting-other-entities-inside-preupdate-of-doctrine-entity-listener) – yivi Apr 29 '20 at 14:11
  • @yivi. Somewhat but not perfectly. Currently, I am just using lifecycle callbacks and `onFlush` is not one per the docs, and I would like to be consistent with other portions of the app and just use callbacks. `preFlush` is a lifecycle callback and I expect there is a way to add `persist` a new entity in that callback, but haven't figured out how. – user1032531 May 03 '20 at 11:33

0 Answers0