Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change a field's value in preUpdate event listener?

Tags:

doctrine-orm

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?

like image 262
DavidW Avatar asked Jan 19 '12 16:01

DavidW


2 Answers

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);
like image 99
DavidW Avatar answered Oct 27 '22 02:10

DavidW


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
        );
    }
}
like image 31
ruslanix.com Avatar answered Oct 27 '22 04:10

ruslanix.com