Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preUpdate and postUpdate events not triggered on Doctrine 2

I have followed the instructions from this tutorial: http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html, and have created a simple listener, that listens for events dispatched by Doctrine on insert or update of an entity. The preInsert and the postInsert events work fine and are dispatched on the creation of a new entity. However, preUpdate and postUpdate are never called on the update of the entity no matter what. The same goes for onFlush. As a side note, I have a console generated controller that supports the basic CRUD operations, and have left it untouched.

Below are some code snippets to demonstrate the way I am doing this.

config.yml

annotation.listener:
    class: City\AnnotatorBundle\Listener\AnnotationListener
    tags:
        -  { name: doctrine.event_listener, event: postUpdate}

Listener implementation (I have omitted the other functions and left only the postUpdate for simplicity purposes)

class AnnotationListener
{

    public function postUpdate(LifecycleEventArgs $args)
    {
        $entity=$args->getEntity();

        echo $entity->getId();
        die;
    }
}

The entity id is never displayed, and the script continues its execution until it is complete, despite the die at the end of the function.

like image 382
tomor Avatar asked Apr 27 '12 21:04

tomor


1 Answers

Did you forget to add @HasLifecycleCallbacks annotaion? You could use @PreUpdate annotation and skip service definition altogether.

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class YouEntity
{

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpdate(){
        // .... your pre-update logic here
    }
    ....
}

In my opinion this way of attaching events is much easier as you don't have to define new services and listeners explicitly. Also you have direct access to data being updated as this method is locations within your entity.

Now, drawback is that you mix logic with your model and that's something that should be avoided if possible...

You can read more about Lifecycle callbacks here: http://symfony.com/doc/master/cookbook/doctrine/file_uploads.html#using-lifecycle-callbacks

like image 182
Jovan Perovic Avatar answered Oct 19 '22 19:10

Jovan Perovic