Search code examples
mongodbsymfonydoctrine-ormevent-listenerodm

Doctrine EventListener onFlush access to old Document


I can access to the updated document in onFlush eventListerner of Doctrine2. I want complete old document to store it elsewhere as old state.

   public function onFlush(OnFlushEventArgs $eventArgs)
    {
        $dm = $eventArgs->getDocumentManager();

        $uow = $dm->getUnitOfWork();
        foreach ($uow->getScheduledDocumentUpdates() as $document) {
            // $document is updated document
            // $changeSet contains only new and old values
            $changeSet = $uow->getDocumentChangeSet($document);

            // I want the whole old document object as $oldDocument
        }       
    }

How can I access old document not just change set?


Solution

  • Just use the preUpdate event. Example:

    public function preUpdate(PreUpdateEventArgs $event)
    {
        $entity = $event->getEntity(); // the whole entity
        $changeSet = $event->getEntityChangeSet(); // only changed properties
    
        // check if password has been changed
        if ($event->hasChangedField('password')) { 
            // do stuff
        }
    
        /* ... */
    }