How do I change a field's value in preUpdate event listener?
Documentation says:
Changes to fields of the passed entities are not recognized by the flush operation anymore, use the computed change-set passed to the event to modify primitive field values.
But it also says:
getEntityChangeSet() to get a copy of the changeset array. Changes to this returned array do not affect updating.
Does this mean I can not change fields of an entity in preUpdate event listener? If not, how would I go about accomplishing this update?
Apparently you need to recompute the changeset yourself for the changes to take effect:
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
$meta = $em->getClassMetadata(get_class($entity));
$uow->recomputeSingleEntityChangeSet($meta, $entity);
Alternatively you can use PreUpdateEventArgs class (http://www.doctrine-project.org/api/orm/2.2/class-Doctrine.ORM.Event.PreUpdateEventArgs.html). Forexample:
public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof Product)
{
$args->setNewValue(
"discount",
123
);
}
}