Is there a built-in way to get all of the changed/updated fields in a Doctrine 2 entity

zerkms picture zerkms · Jan 29, 2012 · Viewed 69.6k times · Source

Let's suppose I retrieve an entity $e and modify its state with setters:

$e->setFoo('a');
$e->setBar('b');

Is there any possibility to retrieve an array of fields that have been changed?

In case of my example I'd like to retrieve foo => a, bar => b as a result

PS: yes, I know I can modify all the accessors and implement this feature manually, but I'm looking for some handy way of doing this

Answer

Ocramius picture Ocramius · Jan 30, 2012

You can use Doctrine\ORM\EntityManager#getUnitOfWork to get a Doctrine\ORM\UnitOfWork.

Then just trigger changeset computation (works only on managed entities) via Doctrine\ORM\UnitOfWork#computeChangeSets().

You can use also similar methods like Doctrine\ORM\UnitOfWork#recomputeSingleEntityChangeSet(Doctrine\ORM\ClassMetadata $meta, $entity) if you know exactly what you want to check without iterating over the entire object graph.

After that you can use Doctrine\ORM\UnitOfWork#getEntityChangeSet($entity) to retrieve all changes to your object.

Putting it together:

$entity = $em->find('My\Entity', 1);
$entity->setTitle('Changed Title!');
$uow = $em->getUnitOfWork();
$uow->computeChangeSets(); // do not compute changes if inside a listener
$changeset = $uow->getEntityChangeSet($entity);

Note. If trying to get the updated fields inside a preUpdate listener, don't recompute change set, as it has already been done. Simply call the getEntityChangeSet to get all of the changes made to the entity.

Warning: As explained in the comments, this solution should not be used outside of Doctrine event listeners. This will break Doctrine's behavior.