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

1.7k views Asked by At

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
1

There are 1 answers

0
Jeroen On BEST ANSWER

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 }