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
Looks like you made a typo:
Notice the ".orm." in the tag name, so for your use case: