5 * Hooks and documentation related to the menu system and links.
9 * @defgroup menu Menu system
11 * Define the navigation menus, local actions and tasks, and contextual links.
13 * @section sec_overview Overview and terminology
14 * The menu system uses routes; see the
15 * @link routing Routing API topic @endlink for more information. It is used
16 * for navigation menus, local tasks, local actions, and contextual links:
17 * - Navigation menus are hierarchies of menu links; links point to routes or
19 * - Menu links and their hierarchies can be defined by Drupal subsystems
20 * and modules, or created in the user interface using the Menu UI module.
21 * - Local tasks are groups of related routes. Local tasks are usually rendered
23 * - Local actions are used for operations such as adding a new item on a page
24 * that lists items of some type. Local actions are usually rendered as
26 * - Contextual links are actions that are related to sections of rendered
27 * output, and are usually rendered as a pop-up list of links. The
28 * Contextual Links module handles the gathering and rendering of contextual
31 * The following sections of this topic provide an overview of the menu API.
32 * For more detailed information, see
33 * https://www.drupal.org/developing/api/8/menu
35 * @section sec_links Defining menu links for the administrative menu
36 * Routes for administrative tasks can be added to the main Drupal
37 * administrative menu hierarchy. To do this, add lines like the following to a
38 * module_name.links.menu.yml file (in the top-level directory for your module):
41 * title: 'Recent log messages'
42 * parent: system.admin_reports
43 * description: 'View events that have recently been logged.'
44 * route_name: dblog.overview
48 * - The first line is the machine name for your menu link, which usually
49 * matches the machine name of the route (given in the 'route_name' line).
50 * - parent: The machine name of the menu link that is the parent in the
51 * administrative hierarchy. See system.links.menu.yml to find the main
52 * skeleton of the hierarchy.
53 * - weight: Lower (negative) numbers come before higher (positive) numbers,
54 * for menu items with the same parent.
56 * Discovered menu links from other modules can be altered using
57 * hook_menu_links_discovered_alter().
59 * @todo Derivatives will probably be defined for these; when they are, add
62 * @section sec_tasks Defining groups of local tasks (tabs)
63 * Local tasks appear as tabs on a page when there are at least two defined for
64 * a route, including the base route as the main tab, and additional routes as
65 * other tabs. Static local tasks can be defined by adding lines like the
66 * following to a module_name.links.task.yml file (in the top-level directory
70 * route_name: book.admin
72 * base_route: book.admin
74 * route_name: book.settings
76 * base_route: book.admin
80 * - The first line is the machine name for your local task, which usually
81 * matches the machine name of the route (given in the 'route_name' line).
82 * - base_route: The machine name of the main task (tab) for the set of local
84 * - weight: Lower (negative) numbers come before higher (positive) numbers,
85 * for tasks on the same base route. If there is a tab whose route
86 * matches the base route, that will be the default/first tab shown.
88 * Local tasks from other modules can be altered using
89 * hook_menu_local_tasks_alter().
91 * @todo Derivatives are in flux for these; when they are more stable, add
94 * @section sec_actions Defining local actions for routes
95 * Local actions can be defined for operations related to a given route. For
96 * instance, adding content is a common operation for the content management
97 * page, so it should be a local action. Static local actions can be
98 * defined by adding lines like the following to a
99 * module_name.links.action.yml file (in the top-level directory for your
103 * route_name: node.add_page
104 * title: 'Add content'
106 * - system.admin_content
109 * - The first line is the machine name for your local action, which usually
110 * matches the machine name of the route (given in the 'route_name' line).
111 * - appears_on: Machine names of one or more routes that this local task
114 * Local actions from other modules can be altered using
115 * hook_menu_local_actions_alter().
117 * @todo Derivatives are in flux for these; when they are more stable, add
118 * documentation here.
120 * @section sec_contextual Defining contextual links
121 * Contextual links are displayed by the Contextual Links module for user
122 * interface elements whose render arrays have a '#contextual_links' element
123 * defined. For example, a block render array might look like this, in part:
126 * '#contextual_links' => array(
128 * 'route_parameters' => array('block' => $entity->id()),
132 * In this array, the outer key 'block' defines a "group" for contextual
133 * links, and the inner array provides values for the route's placeholder
134 * parameters (see @ref sec_placeholders above).
136 * To declare that a defined route should be a contextual link for a
137 * contextual links group, put lines like the following in a
138 * module_name.links.contextual.yml file (in the top-level directory for your
142 * title: 'Configure block'
143 * route_name: 'entity.block.edit_form'
147 * - The first line is the machine name for your contextual link, which usually
148 * matches the machine name of the route (given in the 'route_name' line).
149 * - group: This needs to match the link group defined in the render array.
151 * Contextual links from other modules can be altered using
152 * hook_contextual_links_alter().
154 * @todo Derivatives are in flux for these; when they are more stable, add
155 * documentation here.
157 * @section sec_rendering Rendering menus
158 * Once you have created menus (that contain menu links), you want to render
159 * them. Drupal provides a block (Drupal\system\Plugin\Block\SystemMenuBlock) to
162 * However, perhaps you have more advanced needs and you're not satisfied with
163 * what the menu blocks offer you. If that's the case, you'll want to:
164 * - Instantiate \Drupal\Core\Menu\MenuTreeParameters, and set its values to
165 * match your needs. Alternatively, you can use
166 * MenuLinkTree::getCurrentRouteMenuTreeParameters() to get a typical
167 * default set of parameters, and then customize them to suit your needs.
168 * - Call \Drupal\Core\MenuLinkTree::load() with your menu link tree parameters,
169 * this will return a menu link tree.
170 * - Pass the menu tree to \Drupal\Core\Menu\MenuLinkTree::transform() to apply
171 * menu link tree manipulators that transform the tree. You will almost always
172 * want to apply access checking. The manipulators that you will typically
173 * need can be found in \Drupal\Core\Menu\DefaultMenuLinkTreeManipulators.
174 * - Potentially write a custom menu tree manipulator, see
175 * \Drupal\Core\Menu\DefaultMenuLinkTreeManipulators for examples. This is
176 * only necessary if you want to do things like adding extra metadata to
177 * rendered links to display icons next to them.
178 * - Pass the menu tree to \Drupal\Core\Menu\MenuLinkTree::build(), this will
179 * build a renderable array.
181 * Combined, that would look like this:
183 * $menu_tree = \Drupal::menuTree();
184 * $menu_name = 'my_menu';
186 * // Build the typical default set of menu tree parameters.
187 * $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
189 * // Load the tree based on this set of parameters.
190 * $tree = $menu_tree->load($menu_name, $parameters);
192 * // Transform the tree using the manipulators you want.
193 * $manipulators = array(
194 * // Only show links that are accessible for the current user.
195 * array('callable' => 'menu.default_tree_manipulators:checkAccess'),
196 * // Use the default sorting of menu links.
197 * array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
199 * $tree = $menu_tree->transform($tree, $manipulators);
201 * // Finally, build a renderable array from the transformed tree.
202 * $menu = $menu_tree->build($tree);
204 * $menu_html = drupal_render($menu);
216 * Alters all the menu links discovered by the menu link plugin manager.
218 * @param array $links
219 * The link definitions to be altered.
222 * An array of discovered menu links. Each link has a key that is the machine
223 * name, which must be unique. By default, use the route name as the
224 * machine name. In cases where multiple links use the same route name, such
225 * as two links to the same page in different menus, or two links using the
226 * same route name but different route parameters, the suggested machine name
227 * patten is the route name followed by a dot and a unique suffix. For
228 * example, an additional logout link might have a machine name of
229 * user.logout.navigation, and default links provided to edit the article and
230 * page content types could use machine names
231 * entity.node_type.edit_form.article and entity.node_type.edit_form.page.
232 * Since the machine name may be arbitrary, you should never write code that
233 * assumes it is identical to the route name.
235 * The value corresponding to each machine name key is an associative array
236 * that may contain the following key-value pairs:
237 * - title: (required) The title of the menu link. If this should be
238 * translated, create a \Drupal\Core\StringTranslation\TranslatableMarkup
240 * - description: The description of the link. If this should be
241 * translated, create a \Drupal\Core\StringTranslation\TranslatableMarkup
243 * - route_name: (optional) The route name to be used to build the path.
244 * Either the route_name or url element must be provided.
245 * - route_parameters: (optional) The route parameters to build the path.
246 * - url: (optional) If you have an external link use this element instead of
247 * providing route_name.
248 * - parent: (optional) The machine name of the link that is this link's menu
250 * - weight: (optional) An integer that determines the relative position of
251 * items in the menu; higher-weighted items sink. Defaults to 0. Menu items
252 * with the same weight are ordered alphabetically.
253 * - menu_name: (optional) The machine name of a menu to put the link in, if
254 * not the default Tools menu.
255 * - expanded: (optional) If set to TRUE, and if a menu link is provided for
256 * this menu item (as a result of other properties), then the menu link is
257 * always expanded, equivalent to its 'always expanded' checkbox being set
259 * - options: (optional) An array of options to be passed to
260 * \Drupal\Core\Utility\LinkGeneratorInterface::generate() when generating
261 * a link from this menu item.
265 function hook_menu_links_discovered_alter(&$links) {
266 // Change the weight and title of the user.logout link.
267 $links['user.logout']['weight'] = -10;
268 $links['user.logout']['title'] = new \Drupal\Core\StringTranslation\TranslatableMarkup('Logout');
269 // Conditionally add an additional link with a title that's not translated.
270 if (\Drupal::moduleHandler()->moduleExists('search')) {
271 $links['menu.api.search'] = [
272 'title' => \Drupal::config('system.site')->get('name'),
273 'route_name' => 'menu.api.search',
274 'description' => new \Drupal\Core\StringTranslation\TranslatableMarkup('View popular search phrases for this site.'),
275 'parent' => 'system.admin_reports',
281 * Alter local tasks displayed on the page before they are rendered.
283 * This hook is invoked by \Drupal\Core\Menu\LocalTaskManager::getLocalTasks().
284 * The system-determined tabs and actions are passed in by reference. Additional
287 * The local tasks are under the 'tabs' element and keyed by plugin ID.
289 * Each local task is an associative array containing:
290 * - #theme: The theme function to use to render.
291 * - #link: An associative array containing:
292 * - title: The localized title of the link.
293 * - url: a Url object.
294 * - localized_options: An array of options to pass to
295 * \Drupal\Core\Utility\LinkGeneratorInterface::generate().
296 * - #weight: The link's weight compared to other links.
297 * - #active: Whether the link should be marked as 'active'.
300 * An associative array containing list of (up to 2) tab levels that contain a
301 * list of tabs keyed by their href, each one being an associative array
302 * as described above.
303 * @param string $route_name
304 * The route name of the page.
308 function hook_menu_local_tasks_alter(&$data, $route_name) {
310 // Add a tab linking to node/add to all pages.
311 $data['tabs'][0]['node.add_page'] = [
312 '#theme' => 'menu_local_task',
314 'title' => t('Example tab'),
315 'url' => Url::fromRoute('node.add_page'),
316 'localized_options' => [
318 'title' => t('Add content'),
326 * Alter local actions plugins.
328 * @param array $local_actions
329 * The array of local action plugin definitions, keyed by plugin ID.
331 * @see \Drupal\Core\Menu\LocalActionInterface
332 * @see \Drupal\Core\Menu\LocalActionManager
336 function hook_menu_local_actions_alter(&$local_actions) {
340 * Alter local tasks plugins.
342 * @param array $local_tasks
343 * The array of local tasks plugin definitions, keyed by plugin ID.
345 * @see \Drupal\Core\Menu\LocalTaskInterface
346 * @see \Drupal\Core\Menu\LocalTaskManager
350 function hook_local_tasks_alter(&$local_tasks) {
351 // Remove a specified local task plugin.
352 unset($local_tasks['example_plugin_id']);
356 * Alter contextual links before they are rendered.
358 * This hook is invoked by
359 * \Drupal\Core\Menu\ContextualLinkManager::getContextualLinkPluginsByGroup().
360 * The system-determined contextual links are passed in by reference. Additional
361 * links may be added and existing links can be altered.
363 * Each contextual link contains the following entries:
364 * - title: The localized title of the link.
365 * - route_name: The route name of the link.
366 * - route_parameters: The route parameters of the link.
367 * - localized_options: An array of URL options.
368 * - (optional) weight: The weight of the link, which is used to sort the links.
371 * @param array $links
372 * An associative array containing contextual links for the given $group,
373 * as described above. The array keys are used to build CSS class names for
374 * contextual links and must therefore be unique for each set of contextual
376 * @param string $group
377 * The group of contextual links being rendered.
378 * @param array $route_parameters
379 * The route parameters passed to each route_name of the contextual links.
382 * array('node' => $node->id())
385 * @see \Drupal\Core\Menu\ContextualLinkManager
389 function hook_contextual_links_alter(array &$links, $group, array $route_parameters) {
390 if ($group == 'menu') {
391 // Dynamically use the menu name for the title of the menu_edit contextual
393 $menu = \Drupal::entityManager()->getStorage('menu')->load($route_parameters['menu']);
394 $links['menu_edit']['title'] = t('Edit menu: @label', ['@label' => $menu->label()]);
399 * Alter the plugin definition of contextual links.
401 * @param array $contextual_links
402 * An array of contextual_links plugin definitions, keyed by contextual link
403 * ID. Each entry contains the following keys:
404 * - title: The displayed title of the link
405 * - route_name: The route_name of the contextual link to be displayed
406 * - group: The group under which the contextual links should be added to.
407 * Possible values are e.g. 'node' or 'menu'.
409 * @see \Drupal\Core\Menu\ContextualLinkManager
413 function hook_contextual_links_plugins_alter(array &$contextual_links) {
414 $contextual_links['menu_edit']['title'] = 'Edit the menu';
418 * Perform alterations to the breadcrumb built by the BreadcrumbManager.
420 * @param \Drupal\Core\Breadcrumb\Breadcrumb $breadcrumb
421 * A breadcrumb object returned by BreadcrumbBuilderInterface::build().
422 * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
423 * The current route match.
424 * @param array $context
425 * May include the following key:
426 * - builder: the instance of
427 * \Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface that constructed this
428 * breadcrumb, or NULL if no builder acted based on the current attributes.
432 function hook_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
433 // Add an item to the end of the breadcrumb.
434 $breadcrumb->addLink(\Drupal\Core\Link::createFromRoute(t('Text'), 'example_route_name'));
438 * Alter the parameters for links.
440 * @param array $variables
441 * An associative array of variables defining a link. The link may be either a
442 * "route link" using \Drupal\Core\Utility\LinkGenerator::link(), which is
443 * exposed as the 'link_generator' service or a link generated by
444 * \Drupal\Core\Utility\LinkGeneratorInterface::generate(). If the link is a
445 * "route link", 'route_name' will be set; otherwise, 'path' will be set.
446 * The following keys can be altered:
447 * - text: The link text for the anchor tag. If the hook implementation
448 * changes this text it needs to preserve the safeness of the original text.
449 * Using t() or \Drupal\Component\Utility\SafeMarkup::format() with
450 * @placeholder is recommended as this will escape the original text if
451 * necessary. If the resulting text is not marked safe it will be escaped.
452 * - url_is_active: Whether or not the link points to the currently active
454 * - url: The \Drupal\Core\Url object.
455 * - options: An associative array of additional options that will be passed
456 * to either \Drupal\Core\Utility\UnroutedUrlAssembler::assemble() or
457 * \Drupal\Core\Routing\UrlGenerator::generateFromRoute() to generate the
458 * href attribute for this link, and also used when generating the link.
459 * Defaults to an empty array. It may contain the following elements:
460 * - 'query': An array of query key/value-pairs (without any URL-encoding) to
462 * - absolute: Whether to force the output to be an absolute link (beginning
463 * with http:). Useful for links that will be displayed outside the site,
464 * such as in an RSS feed. Defaults to FALSE.
465 * - language: An optional language object. May affect the rendering of
466 * the anchor tag, such as by adding a language prefix to the path.
467 * - attributes: An associative array of HTML attributes to apply to the
468 * anchor tag. If element 'class' is included, it must be an array; 'title'
469 * must be a string; other elements are more flexible, as they just need
470 * to work as an argument for the constructor of the class
471 * Drupal\Core\Template\Attribute($options['attributes']).
473 * @see \Drupal\Core\Utility\UnroutedUrlAssembler::assemble()
474 * @see \Drupal\Core\Routing\UrlGenerator::generateFromRoute()
476 function hook_link_alter(&$variables) {
477 // Add a warning to the end of route links to the admin section.
478 if (isset($variables['route_name']) && strpos($variables['route_name'], 'admin') !== FALSE) {
479 $variables['text'] = t('@text (Warning!)', ['@text' => $variables['text']]);
484 * @} End of "addtogroup hooks".