Search code examples
symfonydoctrine-ormsymfony5symfony-eventdispatcher

Symfony (5.1) Doctrine Event Listener is fired but not Entity Listener


Using Symfony official documentation, I was cleaning up some code and wanted to replace a Doctrine event listener in Symfony (working):

namespace App\EventListener;

use App\Entity\Comment;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class CommentAuthorAssignmentListener
{
    private $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function prePersist(Comment $comment, LifecycleEventArgs $event)
    {
        dump($comment, $event); exit;
        $comment->setAuthor($this->tokenStorage->getToken()->getUser());
    }
}
services:
    App\EventListener\CommentAuthorAssignmentListener:
        autowire: true 
        tags:
            - { name: doctrine.event_listener, event: prePersist }

With a more specific Entity listener (no error but not fired up at all):

namespace App\EventListener;

use App\Entity\Comment;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class CommentAuthorAssignmentListener
{
    private $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function prePersist(Comment $comment, LifecycleEventArgs $event)
    {
        $comment->setAuthor($this->tokenStorage->getToken()->getUser());
    }
}
services:
    App\EventListener\CommentAuthorAssignmentListener:
        autowire: true 
        tags:
            - { name: doctrine.entity_listener , entity: 'App\Entity\Comment', event: prePersist }

Some notes:

  • I did run cache:clear
  • Use case: explicitely persisting (a freshly created) Comment

Solution

  • Looks like you made a typo:

     # these are the options required to define the entity listener
     name: 'doctrine.orm.entity_listener'
     event: 'postUpdate'
     entity: 'App\Entity\User'
    

    Notice the ".orm." in the tag name, so for your use case:

    services:
        App\EventListener\CommentAuthorAssignmentListener:
            autowire: true 
            tags:
                - { name: doctrine.orm.entity_listener , entity: 'App\Entity\Comment', event: prePersist }