I am trying to restrict access for non admin users on admin/structure/menu so that only admins can create any new links via admin/structure/menu.
Now I want that for one special menu with the ID "Focus" the "Add Link" button is available for another role too.
Here is a Screenshot of the actual backend with the "Add Link" still availabe. I want this to be gone for Hauptnavigation but not for Fokusnavigation.
Same thing when you click on a Menu. You get an "Add Link" button. I can disable this with me code below, but I don't know how to allow it for non Admin Roles again.
I can get the menu->id() in the my_menu.module file, with the same code like in the routesubscriber below but somehow it doesn't work in the routesubscriber. Drush CR returns an
PHP Fatal error: Uncaught Error: Call to a member function id() on null in /var/www/html/web/modules/custom/my_menu/src/Routing/RouteSubscriber.php:31
Stack trace:
#0 /var/www/html/web/core/lib/Drupal/Core/Routing/RouteSubscriberBase.php(37): Drupal\my_menu\Routing\RouteSubscriber->alterRoutes(Object(Symfony\Component\Routing\RouteCollection))
#1 [internal function]: Drupal\Core\Routing\RouteSubscriberBase->onAlterRoutes(Object(Drupal\Core\Routing\RouteBuildEvent), 'routing.route_a...', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#2 /var/www/html/web/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php(142): call_user_func(Array, Object(Drupal\Core\Routing\RouteBuildEvent), 'routing.route_a...', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#3 /var/www/html/web/core/lib/Drupal/Core/Routing/RouteBuilder.php(189): Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch(Object(Drupal\Core\Routing\RouteBuildEvent), 'routing.route_a...')
in /var/www/html/web/modules/custom/my_menu/src/Routing/RouteSubscriber.php on line 31
Are there other ways to get the value? What am I doing wrong.
Here is my code.
<?php
namespace Drupal\my_menu\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\RouteCollection;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Class RouteSubscriber
*
* hiding menu editing components for non-admins
*
* @package Drupal\hw_menu\Routing
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
public function alterRoutes(RouteCollection $collection) {
if ($route = $collection->get('entity.menu.add_link_form')) {
// dpm($route->getRequirements());
$menu instanceof \Drupal\system\Entity\Menu;
$menu = \Drupal::routeMatch()->getParameter('menu');
if($menu->id() != 'focus') {
$route->setRequirement('_role', 'administrator');
}
// dpm($route->getRequirements());
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
// Run after content_translation, which has priority -210.
$events[RoutingEvents::ALTER] = ['onAlterRoutes', -230];
return $events;
}
}