Parisa
Parisa

Reputation: 801

Do something when one special field changes (doctrine)

I use symfony2 with doctrine. I want to do some changes when special attributes of an entity changes; actually I want to save the changes of my attributes and have an status of it's changes. How can i say for example when any field changes do something relevant to the changed field's name.

for example if email changed, add some row to the other entity.

thanks.

Upvotes: 1

Views: 3350

Answers (2)

João Alves
João Alves

Reputation: 1941

As addition to Yan answer, Doctrine already has methods for your needs like hasChangedField, getNewValue.. You can read more here:

http://doctrine-orm.readthedocs.org/en/latest/reference/events.html#preupdate

Upvotes: 1

Yann Eugoné
Yann Eugoné

Reputation: 1361

You should be able to do something with Doctrine Listeners and UnitOfWork changeset, something like this :

use Doctrine\ORM\Event\LifecycleEventArgs;

class DoctrineListener
{
    public function preUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $entityManager = $args->getEntityManager();

        if ($entity instanceof MyEntityClass) {
            $changeSet = $entityManager->getUnitOfWork()->getEntityChangeSet($entity);
            if (isset($changeSet['my_field'])) {
                //do something here
            }
        }
    }
}

For example, this is how some of the Doctrine extensions are registering their changes.

Upvotes: 7

Related Questions