Building a drupal 10 module. How do I subscribe to the UserLogoutEvent
- User
Building a drupal 10 module. How do I subscribe to the UserLogoutEvent
- Assistant
Building a drupal 10 module. How do I subscribe to the UserLogoutEvent
Subscribing to events in Drupal 10 involves creating an event subscriber that listens for specific events and defines the actions that should take place when those events are dispatched. Here are the steps to subscribe to the UserLogoutEvent in your custom module:
First, ensure you have the module's info file (e.g., my_module.info.yml):
name: 'My Custom Module'
type: module
description: 'An example module to demonstrate subscribing to the UserLogoutEvent.'
core_version_requirement: ^10
package: Custom
dependencies:
- drupal:user
You'll need to create an event subscriber class that implements the EventSubscriberInterface. This class will define the method that handles the UserLogoutEvent.
Create a file at src/EventSubscriber/UserLogoutSubscriber.php:
namespace Drupal\my_module\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\user\Event\UserLogoutEvent;
/**
* Subscribes to the user logout event.
*/
class UserLogoutSubscriber implements EventSubscriberInterface {
/**
* Responds to user logout event.
*
* @param \Drupal\user\Event\UserLogoutEvent $event
* The user logout event.
*/
public function onUserLogout(UserLogoutEvent $event) {
// Get the user object.
$account = $event->getAccount();
// Perform your custom logic here.
\Drupal::messenger()->addStatus(t('User %name has logged out.', ['%name' => $account->getDisplayName()]));
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
// Subscribe to the user.logout event.
return [
UserLogoutEvent::class => 'onUserLogout',
];
}
}
You need to declare the event subscriber as a service in your module's services.yml file (e.g., my_module.services.yml):
services:
my_module.user_logout_subscriber:
class: Drupal\my_module\EventSubscriber\UserLogoutSubscriber
tags:
- { name: event_subscriber }
After adding the code, clear the cache to ensure that Drupal recognizes your new service and event subscriber.
You can clear the cache by running:
drush cr
or via the Drupal admin interface at /admin/config/development/performance.
With these steps, you have successfully created a custom module in Drupal 10 that subscribes to the UserLogoutEvent. This event will trigger your custom logic every time a user logs out of the website.