Tài Nguyễn
Tài Nguyễn

Reputation: 133

symfony2 doctrine mongodb - how to check a field in document is updated

In doctrine mongodb of symfony2, is there a way to catch an even postUpdate or onFlush or preUpdate to check if a field in a document is updated? Example that I have is a document Post which has fields: Id, name, description. I have a Listener service to catch the event when Post is updated.

<?php

namespace Acme\Bundle\PostBundle\Listener;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;

public function postUpdate(LifecycleEventArgs $eventArgs)
    {
        /* @var $odm DocumentManager */
        $odm = $eventArgs->getDocumentManager();
        $object = $eventArgs->getDocument();

        if ($object instanceOf Post) {
          // how to check if description field is updated
        }
    }

Upvotes: 0

Views: 598

Answers (1)

malarzm
malarzm

Reputation: 2966

During preUpdate you can check document's change set:

public function preUpdate(PreUpdateEventArgs $e)
{
    $e->getDocumentChangeSet();
    $e->hasChangedField('description')
}

Changeset is associative tuple which looks like

[ 'description' => [ 'old value', 'new value' ] ]

For more available methods you can check out PreUpdateEventArgs class

Upvotes: 1

Related Questions