Finding out what changed via postUpdate listener i

2019-04-06 14:45发布

I have a postUpdate listener and I'd like to know what the values were prior to the update and what the values for the DB entry were after the update. Is there a way to do this in Symfony 2.1? I've looked at what's stored in getUnitOfWork() but it's empty since the update has already taken place.

4条回答
我想做一个坏孩纸
2楼-- · 2019-04-06 15:22

You can find example in doctrine documentation.

class NeverAliceOnlyBobListener
{
    public function preUpdate(PreUpdateEventArgs $eventArgs)
    {
        if ($eventArgs->getEntity() instanceof User) {
            if ($eventArgs->hasChangedField('name') && $eventArgs->getNewValue('name') == 'Alice') {
                $eventArgs->setNewValue('name', 'Bob');
            }
        }
    }
}
查看更多
成全新的幸福
3楼-- · 2019-04-06 15:24

You can use this ansfer Symfony2 - Doctrine - no changeset in post update

/**
 * @param LifecycleEventArgs $args
 */
public function postUpdate(LifecycleEventArgs $args)
{
    $changeArray = $args->getEntityManager()->getUnitOfWork()->getEntityChangeSet($args->getObject());
}
查看更多
Juvenile、少年°
4楼-- · 2019-04-06 15:28

Found the solution here. What I needed was actually part of preUpdate(). I needed to call getEntityChangeSet() on the LifecycleEventArgs.

My code:

public function preUpdate(Event\LifecycleEventArgs $eventArgs)
{   
    $changeArray = $eventArgs->getEntityChangeSet();

    //do stuff with the change array

}
查看更多
再贱就再见
5楼-- · 2019-04-06 15:39

Your Entitiy:

/**
 * Order
 *
 * @ORM\Table(name="order")
 * @ORM\Entity()
 * @ORM\EntityListeners(
 *     {"\EventListeners\OrderListener"}
 * )
 */
class Order
{
...

Your listener:

class OrderListener
{
    protected $needsFlush = false;
    protected $fields = false;

    public function preUpdate($entity, LifecycleEventArgs $eventArgs)
    {
        if (!$this->isCorrectObject($entity)) {
            return null;
        }

        return $this->setFields($entity, $eventArgs);
    }


    public function postUpdate($entity, LifecycleEventArgs $eventArgs)
    {
        if (!$this->isCorrectObject($entity)) {
            return null;
        }

        foreach ($this->fields as $field => $detail) {
            echo $field. ' was  ' . $detail[0]
                       . ' and is now ' . $detail[1];

            //this is where you would save something
        }

        $eventArgs->getEntityManager()->flush();

        return true;
    }

    public function setFields($entity, LifecycleEventArgs $eventArgs)
    {
        $this->fields = array_diff_key(
            $eventArgs->getEntityChangeSet(),
            [ 'modified'=>0 ]
        );

        return true;
    }

    public function isCorrectObject($entity)
    {
        return $entity instanceof Order;
    }
}
查看更多
登录 后发表回答