function hook_contextual_links_alter

Same name in other branches
  1. 9 core/lib/Drupal/Core/Menu/menu.api.php \hook_contextual_links_alter()
  2. 10 core/lib/Drupal/Core/Menu/menu.api.php \hook_contextual_links_alter()
  3. 11.x core/lib/Drupal/Core/Menu/menu.api.php \hook_contextual_links_alter()

Alter contextual links before they are rendered.

This hook is invoked by \Drupal\Core\Menu\ContextualLinkManager::getContextualLinkPluginsByGroup(). The system-determined contextual links are passed in by reference. Additional links may be added and existing links can be altered.

Each contextual link contains the following entries:

  • title: The localized title of the link.
  • route_name: The route name of the link.
  • route_parameters: The route parameters of the link.
  • localized_options: An array of URL options.
  • (optional) weight: The weight of the link, which is used to sort the links.

Parameters

array $links: An associative array containing contextual links for the given $group, as described above. The array keys are used to build CSS class names for contextual links and must therefore be unique for each set of contextual links.

string $group: The group of contextual links being rendered.

array $route_parameters: The route parameters passed to each route_name of the contextual links. For example:

array(
    'node' => $node->id(),
);

See also

\Drupal\Core\Menu\ContextualLinkManager

Related topics

1 invocation of hook_contextual_links_alter()
ContextualLinkManager::getContextualLinksArrayByGroup in core/lib/Drupal/Core/Menu/ContextualLinkManager.php
Gets the contextual links prepared as expected by links.html.twig.

File

core/lib/Drupal/Core/Menu/menu.api.php, line 399

Code

function hook_contextual_links_alter(array &$links, $group, array $route_parameters) {
    if ($group == 'menu') {
        // Dynamically use the menu name for the title of the menu_edit contextual
        // link.
        $menu = \Drupal::entityTypeManager()->getStorage('menu')
            ->load($route_parameters['menu']);
        $links['menu_edit']['title'] = t('Edit menu: @label', [
            '@label' => $menu->label(),
        ]);
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.