Do not use preUpdate or postUpdate, you will have problems. Take a look at OnFlush instead.
At this point, you have access to the complete set of changes so that you can find out which fields have been changed, what has been added, etc. You can also safely save new objects. Note, as the documentation says , you will have to recount the change sets when you save or modify the objects.
The simple example that I put together did not test, but something similar to this will give you what you want.
public function onFlush(OnFlushEventArgs $args) {
$entityManager = $args->getEntityManager();
$unitOfWork = $entityManager->getUnitOfWork();
$updatedEntities = $unitOfWork->getScheduledEntityUpdates();
foreach ($updatedEntities as $updatedEntity) {
if ($updatedEntity instanceof YourEntity) {
$changeset = $unitOfWork->getEntityChangeSet($updatedEntity);
if (!is_array($changeset)) {
return null;
}
if (array_key_exists('someFieldInYourEntity', $changeset)) {
$changes = $changeset['someFieldInYourEntity'];
$previousValueForField = array_key_exists(0, $changes) ? $changes[0] : null;
$newValueForField = array_key_exists(1, $changes) ? $changes[1] : null;
if ($previousValueForField != $newValueForField) {
$yourChangeTrackingEntity = new YourChangeTrackingEntity();
$yourChangeTrackingEntity->setSomeFieldChanged($previousValueForField);
$yourChangeTrackingEntity->setSomeFieldChangedTo($newValueForField);
$entityManager->persist($yourChangeTrackingEntity);
$metaData = $entityManager->getClassMetadata('YourNameSpace\YourBundle\Entity\YourChangeTrackingEntity');
$unitOfWork->computeChangeSet($metaData, $yourChangeTrackingEntity);
}
}
}
}
}
source
share