Search code examples
symfonydoctrine-odm

Doctrine Mongodb getOriginalDocumentData on embedded document


In my symfony application i've got my event_subscriber

CoreBundle\EventSubscriber\CloseIssueSubscriber:
        tags:
            - { name: doctrine_mongodb.odm.event_subscriber, connection: default }

My subscriber simply listen to postPersist and postUpdate events:

public function getSubscribedEvents()
    {
        return array(
            'postPersist',
            'postUpdate',
        );
    }

    public function postPersist(LifecycleEventArgs $args)
    {
        $this->index($args);
    }

    public function postUpdate(LifecycleEventArgs $args)
    {
        $this->index($args);
    }

In my index function what I need to do is to get if certain field has changed in particular the issue.status field.

public function index(LifecycleEventArgs $args)
    {
        $document = $args->getEntity();

            $originalData = $uow->getOriginalDocumentData($document);

            $originalStatus = $originalData && !empty($originalData['issue']) ? $originalData['issue']->getStatus() : null;
            var_dump($originalStatus);
            var_dump($document->getIssue()->getStatus());die;
    }

In my test what I do is change the issue.status field so I expect to receive 2 different values from the var_dump but instead I got the last status from both.

My document is simply something like that:

class Payload
{
/**
 * @ODM\Id
 */
private $id;

/**
 * @ODM\EmbedOne(targetDocument="CoreBundle\Document\Issue\Issue")
 * @Type("CoreBundle\Document\Issue\Issue")
 */
protected $issue;

}

In the embedded issue document status is simply a text field.

I've also try to use the changeset:

$changeset = $uow->getDocumentChangeSet($document);
foreach ($changeset as $fieldName => $change) {
   list($old, $new) = $change;
}
var_dump($old->getStatus());
var_dump($new->getStatus());

Also this two var_dumps returns the same status.


Solution

  • I found the solution to my problem. What malarzm said in the other answer is correct but not the solution to my problem.
    I suppose that I get only one postUpdate/preUpdate postPersist/prePersist just for the Document (Payload) instead I notice that it get called event for the embedded document (don't know why doctrine consider it a persist).

    So the main problem is that I'm waiting for a Payload object instead I have to wait for a Issue object.
    In other hands I was unable to use the getOriginalDocumentData work right even in the postUpdate and in the preUpdate so I have to use the getDocumentChangeSet().