tirenweb
tirenweb

Reputation: 31709

symfony: event listener for entity not working

I have this event listener below, but it is not working:

<?php
namespace Project\BackendBundle\EventListener;
//src/Project/BackendBundle/EventListener/ClippedImagesManager.php
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Project\BackendBundle\Entity\Subitem;
class ClippedImagesManager
{
public function preUpdate(LifecycleEventArgs $args)
{
die("Event listener!!!");
}



//src/Project/BackendBundle/Resources/config/services.yml
services:
    project.clipped_images_manager:
        class: Project\BackendBundle\EventListener\ClippedImagesManager
        tags:
            - { name: doctrine.event_listener, event: preUpdate } 

I expected "Event listener!!" was fired when updating any entity inside BackendBundle.

Upvotes: 0

Views: 3495

Answers (1)

BentCoder
BentCoder

Reputation: 12730

I had a similar issue before. Stripped off example below is same as yours but to see the full working example visit the post please. The trick is, persisting after preUpdate() within postFlush() event.

Note: Although this might not be the best solution, it could be done with an Event Subscriber or simple onFlush() -> $uow->getScheduledEntityUpdates() in an Event Listener.

Service.yml

services:

    entity.event_listener.user_update:
        class:  Site\FrontBundle\EventListener\Entity\UserUpdateListener
        tags:
            - { name: doctrine.event_listener, event: preUpdate }

Event Listener

<?php

namespace Site\FrontBundle\EventListener\Entity;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Site\FrontBundle\Entity\User;

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

        // False check is compulsory otherwise duplication occurs
        if (($entity instanceof User) === false) {
            // Do something
        }
    }
} 

Upvotes: 1

Related Questions