Drupal 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’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\Core\Menu\MenuActiveTrailInterface;
$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.