Here's an updated example for Drupal 9.
Notes
- This does not check for an administrator role; instead, it checks for the
administer content
permission, which all admins have on my site. Make sure the same is true for your site or modify the code.
- This does a redirect on ANY user profile page, not just the user's own profile page. This is different from @tasqyn's code.
- This uses route matching instead of hard-coding the user profile path. This is important because otherwise it will break if you change the user path with something like the Rename Admin Paths module.
mymodule/mymodule.services.yml
services:
my_subscriber:
class: Drupal\mymodule\EventSubscriber\MyEventSubscriber
arguments: ['@request_stack', '@current_route_match', '@current_user']
tags:
- { name: 'event_subscriber' }
mymodule/src/EventSubscriber/MyEventSubscriber.php
<?php
namespace Drupal\mymodule\EventSubscriber;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Event Subscriber MyEventSubscriber.
*/
class MyEventSubscriber implements EventSubscriberInterface {
/**
* The request stack.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* The current route match.
*
* @var \Drupal\Core\Routing\CurrentRouteMatch
*/
protected $currentRouteMatch;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected AccountInterface $currentUser;
/**
* MyEventSubscriber constructor.
*
* @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
* The request stack.
* @param \Drupal\Core\Routing\CurrentRouteMatch $current_route_match
* The current route match.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*/
public function __construct(RequestStack $request_stack, CurrentRouteMatch $current_route_match, AccountInterface $current_user) {
$this->requestStack = $request_stack;
$this->currentRouteMatch = $current_route_match;
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events = [
KernelEvents::REQUEST => 'redirectAuthUsersOnProfile',
];
return $events;
}
/**
* {@inheritdoc}
*/
public function redirectAuthUsersOnProfile(RequestEvent $event) {
$routeName = $this->currentRouteMatch->getRouteName();
if (!$this->currentUser->hasPermission('administer content') &&
$routeName === 'entity.user.canonical') {
$response = new TrustedRedirectResponse('/webapp/index.html', 302);
$event->setResponse($response);
}
}
}