Search code examples
symfonyeventssonata

Sending a mail after creating of an entity | Symfony2 Sonata Admin Bundle


I'd like to create a listener which is supposed to send an email after the creation of an entity.

I am using Sonata Admin Bundle, and I don't quite know what event is associated to the creation of an entity.


Solution

  • You can register Event Listener for Doctrine postFlush event.

    Example listener:

    class PostFlushExampleListener
    {
        public function postFlush(PostFlushEventArgs $args)
        {
            // ...
        }
    }
    

    Service registration in Symfony:

    services:
        my.listener:
            class: PostFlushExampleListener
            tags:
                - { name: doctrine.event_listener, event: postFlush }
    

    Symfony documentation: http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html

    Doctrine documentation: http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/events.html#listening-and-subscribing-to-lifecycle-events