Oct 30, 2020 in Drupal 8
Personally I do not like giving block access to website editors. In this one case, there was a need to edit custom blocks. I granted access to administer blocks, but I blocked access to the overview page with this EventSubscriber.
First, add a file called mymodule.services.yml. Add the following:
services:
mymodule.event_subscriber:
class: Drupal\mymodule\EventSubscriber\CustomRedirects
tags:
- {name: event_subscriber}
Then inside mymodule\src\EventSubscriber\CustomRedirects.php write:
<?php
namespace Drupal\mymodule\EventSubscriber;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Class CustomRedirects
* @package Drupal\mymodule\EventSubscriber
*
* Redirects editors to custom blocks on the block overview page
*/
class CustomRedirects implements EventSubscriberInterface {
public function checkForRedirection(GetResponseEvent $event) {
$request = $event->getRequest();
$path = $request->getRequestUri();
if((strpos($path, 'structure/block') !== false) && (strpos($path, '/block-content') === false)) {
$roles = \Drupal::currentUser()->getRoles();
if(in_array('editor', $roles)) {
// Do something if user has role editor
$newPath = '/admin/structure/block/block-content';
$new_response = new RedirectResponse($newPath, '301');
$new_response->send();
}
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
//The dynamic cache subscribes an event with priority 27. If you want that your code runs before that you have to use a priority >27:
$events[KernelEvents::REQUEST][] = array('checkForRedirection', 29);
return $events;
}
}
A sidenote here: this isn't really preventing editors from editing blocks. If they would have a directlink to /block/edit/whatever-core-block they have access. It is rather a utility help to prevent editors from messing up blocks.