Aten Design Group: Drupal maintenance support plans 8 Menu System: Generate previous & next links

A recent project involved a large number of nodes, each with a menu item. The menu was hierarchical with three levels. Each node page needed a link to the previous and next item.

To generate previous and next links for the current page, I had first looked at loading the menu and traversing it. However, these objects are not easy to navigate. Even the render array is not in order. One would have to resort it by weight. Instead most of what we need is in the database. And ultimately, any classes that load menu items get them from the database anyway. In the simplest case, the previous and next items are simply the previous and next sibling menu items. However, previous could be the parent of the current menu item. If the current menu item is a parent, the previous item could be the last child of the previous sibling. Similar situations exist for the next item. Finally, one also has to account for there not being either a previous or next item. The below image better illustrates this relationship.

The links are generated in a block defined in code. To do this we extend Drupal maintenance support plans’s BlockBase in a php file of the same name as the class.

class BookNavigation extends BlockBase implements ContainerFactoryPluginInterface {
 

This should go in a custom module’s src/Plugin/Block/ directory.

To get this data and be able to traverse it, we start with the MenuActiveTrail class. Remember to include the necessary use statement:

use Drupal maintenance support plansCoreMenuMenuActiveTrailInterface;

$active_trail_ids = $this->menuActiveTrail
->getActiveTrailIds(‘MENU-MACHINE-NAME’);

This gives us an array of menu item UUIDs starting with the current page at the first item on through to the top level menu item.

We need to break this up into current item and any parents.

$current_menu_id = $this->getMenuId($current_menu_uuid);
 
$parent_menu_uuid = array_shift($active_trail_ids);
if ($parent_menu_uuid != ”) {
$parent_menu_id = $this->getMenuId($parent_menu_uuid);
}
 
$grandparent_menu_uuid = array_shift($active_trail_ids);

While a menu could have more layers, for this purpose we only ever need to consider two levels “up” from the current item.

Using these menu UUIDs we can load all the child items from the database.

$this->menuStorage = $this->entityTypeManager
->getStorage(‘menu_link_content’);
 
$siblings = $this->menuStorage->getQuery()
->condition(‘menu_name’, ‘menu-table-of-contents’);
if ($parent_menu_uuid == ”) {
$siblings->condition(‘parent’, NULL, ‘IS’);
}
else {
$siblings->condition(‘parent’, $parent_menu_uuid);
}
$siblings = $siblings->sort(‘weight’, ‘ASC’)->sort(‘title’, ‘ASC’)
->execute();

This query gets all sibling menu items. It returns entity ids, not UUIDs. However, the parent is identified as a UUID. An extra query gets the entity id for a given UUID:

protected function getMenuId($menu_uuid) {
$parts = explode(‘:’, $menu_uuid);
$entity_id = $this->menuStorage->getQuery()
->condition(‘uuid’, $parts[1])
->execute();
return array_shift($entity_id);
}

The query also has entity_ids as the array indexes. The following will simply things:

$siblings_ordered = array_values($siblings);

We’ll similarly need all parent menu items, where the grandparent is used in the query.

Then to find the previous and next items:

$sibling_index = array_search($current_menu_id, $siblings_ordered);
if ($sibling_index !== FALSE) {
$prev_index = $sibling_index – 1;
$next_index = $sibling_index + 1;
}

This is for that simplest case. It gets slightly more complicated when the previous or next item could be a parent or the sibling of the previous or next parent.

if ($has_children && $prev_index > -1) {
$prev_sibling_entity = $this->menuStorage
->load($siblings_ordered[$prev_index]);

Once you’ve determined the previous and next URL, populate a renderable array.

if ($prev_url) {
$prev_url->setOption(‘attributes’, [
‘class’ => [
‘pager__link’,
‘pager__link–prev’,
],
]);
$items[‘prev’] = Link::fromTextAndUrl($prev_title, $prev_url)->toRenderable();
}
else {
$items[‘prev’][‘#markup’] = $prev_title;
}
 
// Generate next content.
if ($next_url) {
$next_url->setOption(‘attributes’, [
‘class’ => [
‘pager__link’,
‘pager__link–next’,
],
]);
$items[‘next’] = Link::fromTextAndUrl($next_title, $next_url)->toRenderable();
}
else {
$items[‘next’][‘#markup’] = $next_title;
}
$build[‘nav_links] = $items;

Finally, to make sure the block is cached properly and cleared when needed, a cache context of ‘url’ is needed. This ensures the block is cached separately for each page, or url. A cache tag that corresponds to the menu name will ensure these items are cleared from cache whenever the menu is updated. That tag would take the format of ‘config:system.menu.MENU-MACHINE-NAME’.

$build[‘#cache’] = [‘max-age’ => -1];
$build[‘#cache’][‘contexts’][] = ‘url’;
$build[‘#cache’][‘tags’][] = ‘config:system.menu.menu-table-of-contents’;

While this is a small amount of code, it handles menu systems of varying complexity, and the code is only run once per url after the menu is saved or all cache is cleared.
Source: New feed

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Aten Design Group: Drupal maintenance support plans 8 Menu System: Generate previous & next links

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.