Symfony unitOfWork

Viewed 180

I have a little problem to solve.

I have two entities with a relation many to mamy (something like posts and tags) I want to have a event that is called onFlush on post entity. The case is that on this event I must have the changes that are made on a collection od tags to that post and the base collection before the changes are made. The first part i know how to make by getScheduledCollectionUpdates but how to get the base collection of the entity that will be updated?

Im using symfony 4.4 and doctrine

1 Answers

You can use a Doctrine Lifecycle Event Subscriber.

You can perform an action the moment before data is written to the database via the preUpdate method. It also gives you access to PreUpdateEventArgs where you can get/modify the data and do what you need.

Create a folder src/EventSubscriber then add this file.

Example

// src/EventSubscriber/YourEntityNameSubscriber.php

namespace App\EventSubscriber;

use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;

class YourEntityNameSubscriber implements EventSubscriberInterface
{
    public function getSubscribedEvents(): array
    {
        return array(
            Events::preUpdate,
        );
    }

    /**
     * On YourEntityName update.
     *
     * @param PreUpdateEventArgs $args
     * @return void
     */
    public function preUpdate(PreUpdateEventArgs $args)
    {
        $entity = $args->getEntity();

        if ($entity instanceof YourEntityName) {
            // Do whatever you need to do here on this specific entity..

            // Example access tags $entity->getTags();
            // You can use $args->hasChangedField('fieldname');
            // Get data $args->getNewValue('fieldname')
            // Also can change data by using $args->setNewValue('fieldname', null);
        }
    }
}
Related