1<?php
2
3/**
4 * @file
5 * Hooks and documentation related to the menu system and links.
6 */
7
8/**
9 * @defgroup menu Menu system
10 * @{
11 * Define the navigation menus, local actions and tasks, and contextual links.
12 *
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
18 *   URLs.
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
22 *   as a group of tabs.
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
25 *   buttons.
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
29 *   links.
30 *
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
34 *
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):
39 * @code
40 * dblog.overview:
41 *   title: 'Recent log messages'
42 *   parent: system.admin_reports
43 *   description: 'View events that have recently been logged.'
44 *   route_name: dblog.overview
45 *   options:
46 *     query:
47 *       uid: 1
48 *   weight: -1
49 * @endcode
50 * Some notes:
51 * - The first line is the machine name for your menu link, which usually
52 *   matches the machine name of the route (given in the 'route_name' line).
53 * - parent: The machine name of the menu link that is the parent in the
54 *   administrative hierarchy. See system.links.menu.yml to find the main
55 *   skeleton of the hierarchy.
56 * - options: Define additional route options such as query parameters. See
57 *   https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-menu-links
58 *   for more information.
59 * - weight: Lower (negative) numbers come before higher (positive) numbers,
60 *   for menu items with the same parent.
61 *
62 * Discovered menu links from other modules can be altered using
63 * hook_menu_links_discovered_alter().
64 *
65 * @todo Derivatives will probably be defined for these; when they are, add
66 *   documentation here.
67 *
68 * @section sec_tasks Defining groups of local tasks (tabs)
69 * Local tasks appear as tabs on a page when there are at least two defined for
70 * a route, including the base route as the main tab, and additional routes as
71 * other tabs. Static local tasks can be defined by adding lines like the
72 * following to a module_name.links.task.yml file (in the top-level directory
73 * for your module):
74 * @code
75 * book.admin:
76 *   route_name: book.admin
77 *   title: 'List'
78 *   base_route: book.admin
79 * book.settings:
80 *   route_name: book.settings
81 *   title: 'Settings'
82 *   base_route: book.admin
83 *   weight: 100
84 * @endcode
85 * Some notes:
86 * - The first line is the machine name for your local task, which usually
87 *   matches the machine name of the route (given in the 'route_name' line).
88 * - base_route: The machine name of the main task (tab) for the set of local
89 *   tasks.
90 * - weight: Lower (negative) numbers come before higher (positive) numbers,
91 *   for tasks on the same base route. If there is a tab whose route
92 *   matches the base route, that will be the default/first tab shown.
93 *
94 * Local tasks from other modules can be altered using
95 * hook_menu_local_tasks_alter().
96 *
97 * @todo Derivatives are in flux for these; when they are more stable, add
98 *   documentation here.
99 *
100 * @section sec_actions Defining local actions for routes
101 * Local actions can be defined for operations related to a given route. For
102 * instance, adding content is a common operation for the content management
103 * page, so it should be a local action. Static local actions can be
104 * defined by adding lines like the following to a
105 * module_name.links.action.yml file (in the top-level directory for your
106 * module):
107 * @code
108 * node.add_page:
109 *   route_name: node.add_page
110 *   title: 'Add content'
111 *   appears_on:
112 *     - system.admin_content
113 * @endcode
114 * Some notes:
115 * - The first line is the machine name for your local action, which usually
116 *   matches the machine name of the route (given in the 'route_name' line).
117 * - appears_on: Machine names of one or more routes that this local task
118 *   should appear on.
119 *
120 * Local actions from other modules can be altered using
121 * hook_menu_local_actions_alter().
122 *
123 * @todo Derivatives are in flux for these; when they are more stable, add
124 *   documentation here.
125 *
126 * @section sec_contextual Defining contextual links
127 * Contextual links are displayed by the Contextual Links module for user
128 * interface elements whose render arrays have a '#contextual_links' element
129 * defined. For example, a block render array might look like this, in part:
130 * @code
131 * array(
132 *   '#contextual_links' => array(
133 *     'block' => array(
134 *       'route_parameters' => array('block' => $entity->id()),
135 *     ),
136 *   ),
137 * @endcode
138 * In this array, the outer key 'block' defines a "group" for contextual
139 * links, and the inner array provides values for the route's placeholder
140 * parameters (see @ref sec_placeholders above).
141 *
142 * To declare that a defined route should be a contextual link for a
143 * contextual links group, put lines like the following in a
144 * module_name.links.contextual.yml file (in the top-level directory for your
145 * module):
146 * @code
147 * block_configure:
148 *   title: 'Configure block'
149 *   route_name: 'entity.block.edit_form'
150 *   group: 'block'
151 * @endcode
152 * Some notes:
153 * - The first line is the machine name for your contextual link, which usually
154 *   matches the machine name of the route (given in the 'route_name' line).
155 * - group: This needs to match the link group defined in the render array.
156 *
157 * Contextual links from other modules can be altered using
158 * hook_contextual_links_alter().
159 *
160 * @todo Derivatives are in flux for these; when they are more stable, add
161 *   documentation here.
162 *
163 * @section sec_rendering Rendering menus
164 * Once you have created menus (that contain menu links), you want to render
165 * them. Drupal provides a block (Drupal\system\Plugin\Block\SystemMenuBlock) to
166 * do so.
167 *
168 * However, perhaps you have more advanced needs and you're not satisfied with
169 * what the menu blocks offer you. If that's the case, you'll want to:
170 * - Instantiate \Drupal\Core\Menu\MenuTreeParameters, and set its values to
171 *   match your needs. Alternatively, you can use
172 *   MenuLinkTree::getCurrentRouteMenuTreeParameters() to get a typical
173 *   default set of parameters, and then customize them to suit your needs.
174 * - Call \Drupal\Core\MenuLinkTree::load() with your menu link tree parameters,
175 *   this will return a menu link tree.
176 * - Pass the menu tree to \Drupal\Core\Menu\MenuLinkTree::transform() to apply
177 *   menu link tree manipulators that transform the tree. You will almost always
178 *   want to apply access checking. The manipulators that you will typically
179 *   need can be found in \Drupal\Core\Menu\DefaultMenuLinkTreeManipulators.
180 * - Potentially write a custom menu tree manipulator, see
181 *   \Drupal\Core\Menu\DefaultMenuLinkTreeManipulators for examples. This is
182 *   only necessary if you want to do things like adding extra metadata to
183 *   rendered links to display icons next to them.
184 * - Pass the menu tree to \Drupal\Core\Menu\MenuLinkTree::build(), this will
185 *   build a renderable array.
186 *
187 * Combined, that would look like this:
188 * @code
189 * $menu_tree = \Drupal::menuTree();
190 * $menu_name = 'my_menu';
191 *
192 * // Build the typical default set of menu tree parameters.
193 * $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
194 *
195 * // Load the tree based on this set of parameters.
196 * $tree = $menu_tree->load($menu_name, $parameters);
197 *
198 * // Transform the tree using the manipulators you want.
199 * $manipulators = array(
200 *   // Only show links that are accessible for the current user.
201 *   array('callable' => 'menu.default_tree_manipulators:checkAccess'),
202 *   // Use the default sorting of menu links.
203 *   array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
204 * );
205 * $tree = $menu_tree->transform($tree, $manipulators);
206 *
207 * // Finally, build a renderable array from the transformed tree.
208 * $menu = $menu_tree->build($tree);
209 *
210 * $menu_html = \Drupal::service('renderer')->render($menu);
211 * @endcode
212 *
213 * @}
214 */
215
216/**
217 * @addtogroup hooks
218 * @{
219 */
220
221/**
222 * Alters all the menu links discovered by the menu link plugin manager.
223 *
224 * @param array $links
225 *   The link definitions to be altered.
226 *
227 * @return array
228 *   An array of discovered menu links. Each link has a key that is the machine
229 *   name, which must be unique. By default, use the route name as the
230 *   machine name. In cases where multiple links use the same route name, such
231 *   as two links to the same page in different menus, or two links using the
232 *   same route name but different route parameters, the suggested machine name
233 *   patten is the route name followed by a dot and a unique suffix. For
234 *   example, an additional logout link might have a machine name of
235 *   user.logout.navigation, and default links provided to edit the article and
236 *   page content types could use machine names
237 *   entity.node_type.edit_form.article and entity.node_type.edit_form.page.
238 *   Since the machine name may be arbitrary, you should never write code that
239 *   assumes it is identical to the route name.
240 *
241 *   The value corresponding to each machine name key is an associative array
242 *   that may contain the following key-value pairs:
243 *   - title: (required) The title of the menu link. If this should be
244 *     translated, create a \Drupal\Core\StringTranslation\TranslatableMarkup
245 *     object.
246 *   - description: The description of the link. If this should be
247 *     translated, create a \Drupal\Core\StringTranslation\TranslatableMarkup
248 *     object.
249 *   - route_name: (optional) The route name to be used to build the path.
250 *     Either the route_name or url element must be provided.
251 *   - route_parameters: (optional) The route parameters to build the path.
252 *   - url: (optional) If you have an external link use this element instead of
253 *     providing route_name.
254 *   - parent: (optional) The machine name of the link that is this link's menu
255 *     parent.
256 *   - weight: (optional) An integer that determines the relative position of
257 *     items in the menu; higher-weighted items sink. Defaults to 0. Menu items
258 *     with the same weight are ordered alphabetically.
259 *   - menu_name: (optional) The machine name of a menu to put the link in, if
260 *     not the default Tools menu.
261 *   - expanded: (optional) If set to TRUE, and if a menu link is provided for
262 *     this menu item (as a result of other properties), then the menu link is
263 *     always expanded, equivalent to its 'always expanded' checkbox being set
264 *     in the UI.
265 *   - options: (optional) An array of options to be passed to
266 *     \Drupal\Core\Utility\LinkGeneratorInterface::generate() when generating
267 *     a link from this menu item.
268 *
269 * @ingroup menu
270 */
271function hook_menu_links_discovered_alter(&$links) {
272  // Change the weight and title of the user.logout link.
273  $links['user.logout']['weight'] = -10;
274  $links['user.logout']['title'] = new \Drupal\Core\StringTranslation\TranslatableMarkup('Logout');
275  // Conditionally add an additional link with a title that's not translated.
276  if (\Drupal::moduleHandler()->moduleExists('search')) {
277    $links['menu.api.search'] = [
278      'title' => \Drupal::config('system.site')->get('name'),
279      'route_name' => 'menu.api.search',
280      'description' => new \Drupal\Core\StringTranslation\TranslatableMarkup('View popular search phrases for this site.'),
281      'parent' => 'system.admin_reports',
282    ];
283  }
284}
285
286/**
287 * Alter local tasks displayed on the page before they are rendered.
288 *
289 * This hook is invoked by \Drupal\Core\Menu\LocalTaskManager::getLocalTasks().
290 * The system-determined tabs and actions are passed in by reference. Additional
291 * tabs may be added.
292 *
293 * The local tasks are under the 'tabs' element and keyed by plugin ID.
294 *
295 * Each local task is an associative array containing:
296 * - #theme: The theme function to use to render.
297 * - #link: An associative array containing:
298 *   - title: The localized title of the link.
299 *   - url: a Url object.
300 *   - localized_options: An array of options to pass to
301 *     \Drupal\Core\Utility\LinkGeneratorInterface::generate().
302 * - #weight: The link's weight compared to other links.
303 * - #active: Whether the link should be marked as 'active'.
304 *
305 * @param array $data
306 *   An associative array containing list of (up to 2) tab levels that contain a
307 *   list of tabs keyed by their href, each one being an associative array
308 *   as described above.
309 * @param string $route_name
310 *   The route name of the page.
311 * @param \Drupal\Core\Cache\RefinableCacheableDependencyInterface $cacheability
312 *   The cacheability metadata for the current route's local tasks.
313 *
314 * @ingroup menu
315 */
316function hook_menu_local_tasks_alter(&$data, $route_name, \Drupal\Core\Cache\RefinableCacheableDependencyInterface &$cacheability) {
317
318  // Add a tab linking to node/add to all pages.
319  $data['tabs'][0]['node.add_page'] = [
320      '#theme' => 'menu_local_task',
321      '#link' => [
322          'title' => t('Example tab'),
323          'url' => Url::fromRoute('node.add_page'),
324          'localized_options' => [
325              'attributes' => [
326                  'title' => t('Add content'),
327              ],
328          ],
329      ],
330  ];
331  // The tab we're adding is dependent on a user's access to add content.
332  $cacheability->addCacheContexts(['user.permissions']);
333}
334
335/**
336 * Alter local actions plugins.
337 *
338 * @param array $local_actions
339 *   The array of local action plugin definitions, keyed by plugin ID.
340 *
341 * @see \Drupal\Core\Menu\LocalActionInterface
342 * @see \Drupal\Core\Menu\LocalActionManager
343 *
344 * @ingroup menu
345 */
346function hook_menu_local_actions_alter(&$local_actions) {
347}
348
349/**
350 * Alter local tasks plugins.
351 *
352 * @param array $local_tasks
353 *   The array of local tasks plugin definitions, keyed by plugin ID.
354 *
355 * @see \Drupal\Core\Menu\LocalTaskInterface
356 * @see \Drupal\Core\Menu\LocalTaskManager
357 *
358 * @ingroup menu
359 */
360function hook_local_tasks_alter(&$local_tasks) {
361  // Remove a specified local task plugin.
362  unset($local_tasks['example_plugin_id']);
363}
364
365/**
366 * Alter contextual links before they are rendered.
367 *
368 * This hook is invoked by
369 * \Drupal\Core\Menu\ContextualLinkManager::getContextualLinkPluginsByGroup().
370 * The system-determined contextual links are passed in by reference. Additional
371 * links may be added and existing links can be altered.
372 *
373 * Each contextual link contains the following entries:
374 * - title: The localized title of the link.
375 * - route_name: The route name of the link.
376 * - route_parameters: The route parameters of the link.
377 * - localized_options: An array of URL options.
378 * - (optional) weight: The weight of the link, which is used to sort the links.
379 *
380 *
381 * @param array $links
382 *   An associative array containing contextual links for the given $group,
383 *   as described above. The array keys are used to build CSS class names for
384 *   contextual links and must therefore be unique for each set of contextual
385 *   links.
386 * @param string $group
387 *   The group of contextual links being rendered.
388 * @param array $route_parameters
389 *   The route parameters passed to each route_name of the contextual links.
390 *   For example:
391 *   @code
392 *   array('node' => $node->id())
393 *   @endcode
394 *
395 * @see \Drupal\Core\Menu\ContextualLinkManager
396 *
397 * @ingroup menu
398 */
399function hook_contextual_links_alter(array &$links, $group, array $route_parameters) {
400  if ($group == 'menu') {
401    // Dynamically use the menu name for the title of the menu_edit contextual
402    // link.
403    $menu = \Drupal::entityTypeManager()->getStorage('menu')->load($route_parameters['menu']);
404    $links['menu_edit']['title'] = t('Edit menu: @label', ['@label' => $menu->label()]);
405  }
406}
407
408/**
409 * Alter the plugin definition of contextual links.
410 *
411 * @param array $contextual_links
412 *   An array of contextual_links plugin definitions, keyed by contextual link
413 *   ID. Each entry contains the following keys:
414 *     - title: The displayed title of the link
415 *     - route_name: The route_name of the contextual link to be displayed
416 *     - group: The group under which the contextual links should be added to.
417 *       Possible values are e.g. 'node' or 'menu'.
418 *
419 * @see \Drupal\Core\Menu\ContextualLinkManager
420 *
421 * @ingroup menu
422 */
423function hook_contextual_links_plugins_alter(array &$contextual_links) {
424  $contextual_links['menu_edit']['title'] = 'Edit the menu';
425}
426
427/**
428 * Perform alterations to the breadcrumb built by the BreadcrumbManager.
429 *
430 * @param \Drupal\Core\Breadcrumb\Breadcrumb $breadcrumb
431 *   A breadcrumb object returned by BreadcrumbBuilderInterface::build().
432 * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
433 *   The current route match.
434 * @param array $context
435 *   May include the following key:
436 *   - builder: the instance of
437 *     \Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface that constructed this
438 *     breadcrumb, or NULL if no builder acted based on the current attributes.
439 *
440 * @ingroup menu
441 */
442function hook_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
443  // Add an item to the end of the breadcrumb.
444  $breadcrumb->addLink(\Drupal\Core\Link::createFromRoute(t('Text'), 'example_route_name'));
445}
446
447/**
448 * Alter the parameters for links.
449 *
450 * @param array $variables
451 *   An associative array of variables defining a link. The link may be either a
452 *   "route link" using \Drupal\Core\Utility\LinkGenerator::link(), which is
453 *   exposed as the 'link_generator' service or a link generated by
454 *   \Drupal\Core\Utility\LinkGeneratorInterface::generate(). If the link is a
455 *   "route link", 'route_name' will be set; otherwise, 'path' will be set.
456 *   The following keys can be altered:
457 *   - text: The link text for the anchor tag. If the hook implementation
458 *     changes this text it needs to preserve the safeness of the original text.
459 *     Using t() or \Drupal\Component\Render\FormattableMarkup with
460 *     @placeholder is recommended as this will escape the original text if
461 *     necessary. If the resulting text is not marked safe it will be escaped.
462 *   - url_is_active: Whether or not the link points to the currently active
463 *     URL.
464 *   - url: The \Drupal\Core\Url object.
465 *   - options: An associative array of additional options that will be passed
466 *     to either \Drupal\Core\Utility\UnroutedUrlAssembler::assemble() or
467 *     \Drupal\Core\Routing\UrlGenerator::generateFromRoute() to generate the
468 *     href attribute for this link, and also used when generating the link.
469 *     Defaults to an empty array. It may contain the following elements:
470 *     - 'query': An array of query key/value-pairs (without any URL-encoding) to
471 *       append to the URL.
472 *     - absolute: Whether to force the output to be an absolute link (beginning
473 *       with http:). Useful for links that will be displayed outside the site,
474 *       such as in an RSS feed. Defaults to FALSE.
475 *     - language: An optional language object. May affect the rendering of
476 *       the anchor tag, such as by adding a language prefix to the path.
477 *     - attributes: An associative array of HTML attributes to apply to the
478 *       anchor tag. If element 'class' is included, it must be an array; 'title'
479 *       must be a string; other elements are more flexible, as they just need
480 *       to work as an argument for the constructor of the class
481 *       Drupal\Core\Template\Attribute($options['attributes']).
482 *
483 * @see \Drupal\Core\Utility\UnroutedUrlAssembler::assemble()
484 * @see \Drupal\Core\Routing\UrlGenerator::generateFromRoute()
485 */
486function hook_link_alter(&$variables) {
487  // Add a warning to the end of route links to the admin section.
488  /** @var \Drupal\Core\Url $url */
489  $url = $variables['url'];
490  if ($url->isRouted() && strpos($url->getRouteName(), 'admin') !== FALSE) {
491    $variables['text'] = t('@text (Warning!)', ['@text' => $variables['text']]);
492  }
493}
494
495/**
496 * @} End of "addtogroup hooks".
497 */
498