symfonydoctrine-ormsymfony4

How can I implement a dotrine entity event listener


I'm working with Symfony 4.4, at first I want to check my doctrine version I found: in composer:

doctrine/orm": "^2.4.5

in symfony.lock:

"doctrine/orm": {
    "version": "v2.7.0"
},

which one I have to trust ?

So the main problem is that I'm trying to implement a doctrine entity listener but It didn't work for me:

App\Entity\Admin:

/**
 * @ORM\Entity(repositoryClass="App\Repository\AdminRepository")
 *
 * @ORM\EntityListeners({"AdminListener"})
 */
 class Admin implements UserInterface

services.yaml:

admin_listener:
    class: App\EventListener\Doctrine\AdminListener
    tags:
        -
            name: doctrine.orm.entity_listener
            event: preRemove
            entity: App\Entity\Admin
            method: preRemove
            connection: 'default'

App\EventListener\Doctrine\AdminListener:

namespace App\EventListener\Doctrine;
use Doctrine\Persistence\Event\LifecycleEventArgs;

class AdminListener
{
    public function preRemove(Admin $admin, LifecycleEventArgs $event)
    {
        dump($admin);
        dd($event);
    }

}

#console:

>bin/console debug:event-dispatcher doctrine.orm.entity_listener
#output:                                                                        
 [WARNING] The event "doctrine.orm.entity_listener" does not have any     
           registered listeners.    

  

Solution

  • The problem that I had a DataPersister ( API Platform component ) that disallow the Delete before that attempt the Doctrine level, so for that I thought that the event listener is not working. Otherwise, the event listener is working and there is many alternatives to make it:

    https://symfony.com/doc/4.4/doctrine/events.html