In drupal 10 module development, how do I run code in my module when user_logout
- User
In drupal 10 module development, how do I run code in my module when user_logout
- Assistant
In drupal 10 module development, how do I run code in my module when user_logout
To run code in your Drupal 10 module when a user logs out, you can use an event subscriber to listen for the UserLogoutEvent. Here are the steps to create and register the event subscriber in your custom module:
Create the Custom Module:
If you haven't already created your custom module, you need to set it up. Create a folder for your module in the modules/custom directory of your Drupal installation. For example, you can name it mymodule.
Create the Module Info File:
Inside your custom module folder, create a file named mymodule.info.yml. This file provides metadata about your module. Here is an example of what it might look like:
name: 'My Module'
type: module
description: 'A custom module to perform actions on user logout.'
package: Custom
core_version_requirement: ^10
dependencies:
- drupal:user
Create the Event Subscriber: In your module folder, create a src/EventSubscriber directory to house your event subscriber class. For example:
modules/custom/mymodule/src/EventSubscriber/UserLogoutSubscriber.php
<?php
namespace Drupal\mymodule\EventSubscriber;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
class UserLogoutSubscriber implements EventSubscriberInterface {
/**
* Reacts to user logout events.
*
* @param \Drupal\Core\Session\AccountInterface $account
* The account object of the user that is logging out.
*/
public function onUserLogout(AccountInterface $account) {
// Your custom code here.
\Drupal::logger('mymodule')->notice('User logged out: ' . $account->getDisplayName());
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events['user.logout'][] = ['onUserLogout'];
return $events;
}
}
Register the Event Subscriber:
Next, you need to register your event subscriber service. Create a file named mymodule.services.yml in your module's root directory:
modules/custom/mymodule/mymodule.services.yml
services:
mymodule.user_logout_subscriber:
class: Drupal\mymodule\EventSubscriber\UserLogoutSubscriber
arguments: []
tags:
- { name: event_subscriber }
Enable Your Module: Clear the cache and enable your module using Drush or via the UI:
drush en mymodule
drush cr
Or navigate to /admin/modules and enable your module from the list.
Now, whenever a user logs out, the onUserLogout method in your UserLogoutSubscriber will be triggered, and any code you placed within that method will be executed. For instance, the example above will log a message every time a user logs out.
Not yet included in a published release.