You are here

class MenuBlockTitle in Menu block title 8

Provides methods for preRender hook.

Hierarchy

Expanded class hierarchy of MenuBlockTitle

1 file declares its use of MenuBlockTitle
menu_block_title.module in ./menu_block_title.module
Alters menu block titles to show the active menu item's parent.

File

src/MenuBlockTitle.php, line 10

Namespace

Drupal\menu_block_title
View source
class MenuBlockTitle implements TrustedCallbackInterface {

  /**
   * {@inheritdoc}
   */
  public static function trustedCallbacks() {
    return [
      'preRender',
    ];
  }

  /**
   * The preRender callback which modifies the build output.
   */
  public static function preRender($build) {
    if (!isset($build['#derivative_plugin_id'])) {
      return $build;
    }
    $menu_name = $build['#derivative_plugin_id'];
    $active_menu_item = \Drupal::service('menu.active_trail')
      ->getActiveLink($menu_name);
    if (!$active_menu_item) {
      return $build;
    }

    // If a parent exists, load and use as title.
    if ($active_menu_item
      ->getParent()) {
      $parent_uuid = str_replace('menu_link_content:', '', $active_menu_item
        ->getParent());
      $parent = \Drupal::service('entity.repository')
        ->loadEntityByUuid('menu_link_content', $parent_uuid);
      $linked_title = [
        '#type' => 'link',
        '#url' => $parent
          ->getUrlObject(),
        '#title' => $parent
          ->getTitle(),
      ];
    }
    else {
      return $build;
    }
    $build['#configuration']['label'] = $linked_title;
    return $build;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
MenuBlockTitle::preRender public static function The preRender callback which modifies the build output.
MenuBlockTitle::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.