Skip to main content

Drupal ^8: How to activate a menu item based on a url with query parameters

Recently i discovered that when you render a custom menu on a sidebar and you have a custom pager inside a menu item the active trail is broken. For example let's say we have this menu :

  • Home
  • About
  • Services

and services is a custom dynamic controller index page where you can go forward and backward like this /services?item=1 ,/services?item=2 , /services?item=3 when you are on the default page it is ok the active trail is shown as "active" but when you are at /services?item=1 it wont show as active. This is how you can make it active when you are on the same path with query parameters at the same url.

function atheme_preprocess_menu__booking_manager(&$variables, $hook) {
  //Custom menus that needs to be active
  $in_hook = ['menu__booking_manager', 'menu__attraction_manager', 'menu__general_admin'];

  $items = $variables['items'];
  if (!in_array($hook, $in_hook)) {
    return $variables;
  }

  foreach ($items as $key => $item) {
    $in_path = $item['url']->getInternalPath();
    if (strpos($current_path, 'services') !== false && strpos($in_path, 'services') !== false) {
     //If this is a services?item=1 page set it active too
      $variables['items'][$key]['in_active_trail'] = TRUE;
    }
  }
}

 

custom module php

Latest Articles

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file admin_pixelthi… Sun, 12/01/2024 - 16:49 Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

composer
Controlling ckeditor styling options with hook_editor_js_settings_alter admin_pixelthi… Thu, 05/16/2024 - 10:49 Controlling ckeditor styling options with hook_editor_js_settings_alter

Controlling ckeditor styling options with hook_editor_js_settings_alter

php hook hook_editor_js_settings_alter hook_field_widget_single_[WIDGET_TYPE]_form_alter
Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide admin_pixelthi… Tue, 09/05/2023 - 14:18 Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

composer drupal9 drupal10