How can you contact us

2By phone at +40 749 014 360

If you still have problems, please let us know, by sending an email to Thank you!


Mon-Fri 9:00AM - 6:00AM
Sat - 9:00AM - 1:00PM
Sundays by appointment only!

Drupal 8 - How to subscribe to an event

/ / Drupal 8

In this 'How to' I will show you how to subscribe to an exisitng event.

You can read my previous article on How to dispatch an event.

1 Create a new file in root if your module

In this file, we need to create a new service and tag it as an 'event_subscriber' so Drupal will know that this service is an event subscriber.

    class: Drupal\mymodule\EventSubscriber\Example2
    arguments: []
      - { name: event_subscriber }

2 Create a new class called 'Example2' in \mymodule\src\EventSubscriber\Example2.
In order for this class to be a service subscriber, it needs to implement the \Symfony\Component\EventDispatcher\EventSubscriberInterface intarface.

By implementing the EventSubscriberInterface, we need to implement the getSubscribedEvents() method of that interface.
This method returns an array of event names this subscriber wants to listen to.

     * For instance:
     *  * array('eventName' => 'methodName')
     *  * array('eventName' => array('methodName', $priority))
     *  * array('eventName' => array(array('methodName1', $priority), array('methodName2'))

3 Then, we need to define the methodName that will be called when the event is dispatched.
This method, will get a parameter a class that extends \Symfony\Component\EventDispatcher\Event class.

namespace Drupal\mymodule\EventSubscriber;

use Drupal\othermodule\Event\OtherModuleEvent;
use Drupal\othermodule\Event\OtherModuleEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

 * Class Example2.
 * @package Drupal\mymodule
class Example2 implements EventSubscriberInterface {

   * {@inheritdoc}
  static function getSubscribedEvents() {
    $events[OtherModuleEvents::EVENT_NAME] = ['event_name'];

    return $events;

   * This is the subscriber for OtherModuleEvents::EVENT_NAME.
   * @param \Drupal\othermodule\Event\OtherModuleEvent $event
  public function event_name(OtherModuleEvent $event) {

    // Here we have access to the $event object that was passed from
    // Example2Controller::example1() function.
    drupal_set_message('Event fired in MyModule with message: ' . $event->getMessage());

Sign in your account to have access to different features

Forgot your details?