We have three entities:
- MaterialAssigned
- Stock
- Job
MaterialAssigned
holds three fields:
- Quantity (int)
- Relation with a
Job
Entity - Relation with a
Stock
entity
We are try to write a preUpdate()
on MaterialAssigned which takes old and new Quantity
values, do some calculation and update the overall total quantity in the related Stock
Entity.
When we var_dump()
values along our logic, everything seems to work as expected, however the related Stock
entity never gets updated.
That's the relevant code from the EventListener:
public function preUpdate(PreUpdateEventArgs $eventArgs)
{
$entity = $eventArgs->getEntity();
if ($entity instanceof MaterialAssigned) {
$changeArray = $eventArgs->getEntityChangeSet();
$pre_quantity = $changeArray['quantity'][0];
$post_quantity = $changeArray['quantity'][1];
// Here we call the function to do the calculation, for testing we just use a fixed value
$entity->getStock()->setTotal(9999);
$em = $eventArgs->getEntityManager();
$uow = $em->getUnitOfWork();
$meta = $em->getClassMetadata(get_class($entity));
$uow->recomputeSingleEntityChangeSet($meta, $entity);
}
}
The issue here is that
preUpdate
is restricted by Doctrine to not allow any Entities to be updated from within this method.onFlush
on the other hand does allow the update of Entities, and replaces the need for three separate methods (update, persist, remove).We then found the following guide which hints at a solution: Tobias Sjösten's guide
Our code now looks like:
This is the
print_r()
of$changeArray
: