Drupal 8 - Display submenu in a block

Posted on 19 Mar 2016 by Alexei Raiu
To edit and place a submenu in a block in Drupal 8, place this code in the block plugin class file:
<?php

 
/**
   * {@inheritdoc}
   */
 
public function build() {
   
$menu_tree = \Drupal::menuTree();
   
$menu_name = 'main';
   
$parameters = new MenuTreeParameters();
   
$tree = $menu_tree->load($menu_name, $parameters);
   
$manipulators = array(
      array(
'callable' => 'menu.default_tree_manipulators:checkAccess'),
      array(
'callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
   
$tree = $menu_tree->transform($tree, $manipulators);
   
$subtree = $tree['SUBTREE IDENTIFIER GOES HERE']->subtree;
   
$menu = $menu_tree->build($subtree);
    foreach (
$menu['#items'] as &$item) {
     
$item['url']->setOption('fragment', 'block-aboutussubmenu');
    }
   
$markup = \Drupal::service('renderer')->render($menu);

   
$build = array(
     
'#type' => 'markup',
     
'#markup' => $markup,
    );

    return
$build;
  }

?>
In this case, a fragment was added to each link.
Tags