2

sry if something is not so accurate, but im less experienced with Symfony

I have the following orm mapping:

src/app/ExampleBundle/Resources/config/doctrine/Base.orm.yml

app\ExampleBundle\Entity\Base:
type: mappedSuperclass
fields:
    createdAt:
        type: datetime
        nullable: true
        options:
            default: null
    updatedAt:
        type: datetime
        nullable: true
        options:
            default: null

This creates a entity Base which i modified to be abstract

src/app/ExampleBundle/Entity/Base.php

abstract class Base {
    ...
}

I have some other entities they extend this abstract class e.g.

src/app/ExampleBundle/Entity/Category.php

class Category extends Base
{
    ...
}

Now i tried to add a listener that sets the createdAt/updatedAt datetime on every persist for every entity that extends the Base Entity

src/app/ExampleBundle/EventListener/BaseListener.php

namespace app\ExampleBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\User\UserInterface;
use app\ExampleBundle\Entity\Base;

class BaseListener
{
    protected $tokenStorage;

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

    public function prePersist(Base $base, LifecycleEventArgs $event)
    {
        $user = $this->tokenStorage->getToken()->getUser();
        if (!$user instanceof UserInterface) {
            $user = null;
        }

        if ($base->getCreatedAt() === null) {
            $base->setCreated($user, new \DateTime());
        } else {
            $base->setUpdated($user, new \DateTime());
        }
    }
}

And added it to the bundles services.yml

src/app/ExampleBundle/Resources/config

services:
    app\ExampleBundle\EventListener\BaseListener:
        arguments: ['@security.token_storage']
        tags:
            - { name: doctrine.orm.entity_listener, entity: app\ExampleBundle\Entity\Base, event: prePersist }

Symfony throws no Exception, but the defined event seems also not triggered.

I tried to change the entity param in services to the "real" entity Category, but still no error, nor the event triggered.

I think, i did everything as it is decribed in the documentation. But it still not working.

The command

debug:event-dispatcher

does also not show the event

So, the question is: What did i wrong?

6
  • entity field, in tags, must refer to Category, not Base
    – SilvioQ
    Commented Nov 21, 2018 at 21:00
  • @SilvioQ: 'I tried to change the entity param in services to the "real" entity Category, but still no error, nor the event triggered.'
    – Squall
    Commented Nov 21, 2018 at 21:04
  • 1
    What version of doctrine are you using? If its < 2.5 you need to specify the listener on the entity as well Commented Nov 21, 2018 at 21:11
  • @AndreiDumitrescu-Tudor: "^2.5". I tried to set the lifecycleCallbacks, but they try to trigger some method inside the entity
    – Squall
    Commented Nov 21, 2018 at 21:16
  • Did you try to set HasLifecycleCallbacks() insise the base entity? Commented Nov 21, 2018 at 21:28

3 Answers 3

1

Here the documentation I follow https://symfony.com/doc/3.4/doctrine/event_listeners_subscribers.html

The prePersist method is called for all the entities so you must exclude non instance of app\ExampleBundle\Entity\Base. The first argument is LifecycleEventArgs.

public function prePersist(LifecycleEventArgs $event)
{
    $base = $event->getObject();
    if (!$base instanceof Base) {
        return;
    }
    $user = $this->tokenStorage->getToken()->getUser();
    if (!$user instanceof UserInterface) {
        $user = null;
    }

    if ($base->getCreatedAt() === null) {
        $base->setCreated($user, new \DateTime());
    } else {
        $base->setUpdated($user, new \DateTime());
    }
}

I can recommend you StofDoctrineExtensionsBundle (Timestampable) that does exactly what you want. It based on DoctrineExtensions.

There is even a trait that works like a charm.

6
  • Where does $args come from?
    – cezar
    Commented Nov 21, 2018 at 21:52
  • My Problem is that the prePersist Method does never run. I tried to throw Exception or die() inside the prePersist method, but nothing is called. And thanks for Link to the StofBundle, i will take a look at it.
    – Squall
    Commented Nov 21, 2018 at 21:59
  • 2
    May be, you must change the tag name to doctrine.event_listener (without orm). entity property is not necesary.
    – SilvioQ
    Commented Nov 21, 2018 at 22:08
  • @SilvioQ +1 I missed the tag name
    – acucchieri
    Commented Nov 21, 2018 at 22:24
  • @SilvioQ: I have already tried the doctrine.event_listener, also to set a real entity, omit the entity, set the class param. But nothing seems to trigger the event -.-
    – Squall
    Commented Nov 22, 2018 at 9:25
0

After some research, many more tests, diving into the EntityManager and the UnitOfWork. Nothing seems to work fine. I get it so far to work on doctrine:fixtures:load, but for any reason they still not working if i use the entity manager in the Controllers. So, i decided to try another way with a subscriber.

tags:
    - { name: doctrine.event_subscriber }

class ... implements EventSubscriber

So i still dont know why the Listener did not work as expected, but with the subscribers i found a solution that does.

Thanks to all of you for support :)

0

For Symfony 5 and anybody who will struggle with issue when Events::loadClassMetadata is not fired in subscriber.

Class should implement "EventSubscriberInterface"

class DiscriminatorSubscriber implements EventSubscriberInterface
{

public function getSubscribedEvents()
{
    return [Events::loadClassMetadata];
}

public function loadClassMetadata(LoadClassMetadataEventArgs $event): void
{

}

Than you dont have to do anythng more if you have autoconfigure and autowire on TRUE in your services.yml

Doctrine will handle your subscriber registration (check DoctrineExtension.php)

 $container->registerForAutoconfiguration(EventSubscriberInterface::class)
        ->addTag('doctrine.event_subscriber');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.