Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / lib / Drupal / Core / Menu / menu.api.php
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  *   weight: -1
46  * @endcode
47  * Some notes:
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.
55  *
56  * Discovered menu links from other modules can be altered using
57  * hook_menu_links_discovered_alter().
58  *
59  * @todo Derivatives will probably be defined for these; when they are, add
60  *   documentation here.
61  *
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
67  * for your module):
68  * @code
69  * book.admin:
70  *   route_name: book.admin
71  *   title: 'List'
72  *   base_route: book.admin
73  * book.settings:
74  *   route_name: book.settings
75  *   title: 'Settings'
76  *   base_route: book.admin
77  *   weight: 100
78  * @endcode
79  * Some notes:
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
83  *   tasks.
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.
87  *
88  * Local tasks from other modules can be altered using
89  * hook_menu_local_tasks_alter().
90  *
91  * @todo Derivatives are in flux for these; when they are more stable, add
92  *   documentation here.
93  *
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
100  * module):
101  * @code
102  * node.add_page:
103  *   route_name: node.add_page
104  *   title: 'Add content'
105  *   appears_on:
106  *     - system.admin_content
107  * @endcode
108  * Some notes:
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
112  *   should appear on.
113  *
114  * Local actions from other modules can be altered using
115  * hook_menu_local_actions_alter().
116  *
117  * @todo Derivatives are in flux for these; when they are more stable, add
118  *   documentation here.
119  *
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:
124  * @code
125  * array(
126  *   '#contextual_links' => array(
127  *     'block' => array(
128  *       'route_parameters' => array('block' => $entity->id()),
129  *     ),
130  *   ),
131  * @endcode
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).
135  *
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
139  * module):
140  * @code
141  * block_configure:
142  *   title: 'Configure block'
143  *   route_name: 'entity.block.edit_form'
144  *   group: 'block'
145  * @endcode
146  * Some notes:
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.
150  *
151  * Contextual links from other modules can be altered using
152  * hook_contextual_links_alter().
153  *
154  * @todo Derivatives are in flux for these; when they are more stable, add
155  *   documentation here.
156  *
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
160  * do so.
161  *
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.
180  *
181  * Combined, that would look like this:
182  * @code
183  * $menu_tree = \Drupal::menuTree();
184  * $menu_name = 'my_menu';
185  *
186  * // Build the typical default set of menu tree parameters.
187  * $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
188  *
189  * // Load the tree based on this set of parameters.
190  * $tree = $menu_tree->load($menu_name, $parameters);
191  *
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'),
198  * );
199  * $tree = $menu_tree->transform($tree, $manipulators);
200  *
201  * // Finally, build a renderable array from the transformed tree.
202  * $menu = $menu_tree->build($tree);
203  *
204  * $menu_html = \Drupal::service('renderer')->render($menu);
205  * @endcode
206  *
207  * @}
208  */
209
210 /**
211  * @addtogroup hooks
212  * @{
213  */
214
215 /**
216  * Alters all the menu links discovered by the menu link plugin manager.
217  *
218  * @param array $links
219  *   The link definitions to be altered.
220  *
221  * @return array
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.
234  *
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
239  *     object.
240  *   - description: The description of the link. If this should be
241  *     translated, create a \Drupal\Core\StringTranslation\TranslatableMarkup
242  *     object.
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
249  *     parent.
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
258  *     in the UI.
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.
262  *
263  * @ingroup menu
264  */
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',
276     ];
277   }
278 }
279
280 /**
281  * Alter local tasks displayed on the page before they are rendered.
282  *
283  * This hook is invoked by \Drupal\Core\Menu\LocalTaskManager::getLocalTasks().
284  * The system-determined tabs and actions are passed in by reference. Additional
285  * tabs may be added.
286  *
287  * The local tasks are under the 'tabs' element and keyed by plugin ID.
288  *
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'.
298  *
299  * @param array $data
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.
305  * @param \Drupal\Core\Cache\RefinableCacheableDependencyInterface $cacheability
306  *   The cacheability metadata for the current route's local tasks.
307  *
308  * @ingroup menu
309  */
310 function hook_menu_local_tasks_alter(&$data, $route_name, \Drupal\Core\Cache\RefinableCacheableDependencyInterface &$cacheability) {
311
312   // Add a tab linking to node/add to all pages.
313   $data['tabs'][0]['node.add_page'] = [
314       '#theme' => 'menu_local_task',
315       '#link' => [
316           'title' => t('Example tab'),
317           'url' => Url::fromRoute('node.add_page'),
318           'localized_options' => [
319               'attributes' => [
320                   'title' => t('Add content'),
321               ],
322           ],
323       ],
324   ];
325   // The tab we're adding is dependent on a user's access to add content.
326   $cacheability->addCacheTags(['user.permissions']);
327 }
328
329 /**
330  * Alter local actions plugins.
331  *
332  * @param array $local_actions
333  *   The array of local action plugin definitions, keyed by plugin ID.
334  *
335  * @see \Drupal\Core\Menu\LocalActionInterface
336  * @see \Drupal\Core\Menu\LocalActionManager
337  *
338  * @ingroup menu
339  */
340 function hook_menu_local_actions_alter(&$local_actions) {
341 }
342
343 /**
344  * Alter local tasks plugins.
345  *
346  * @param array $local_tasks
347  *   The array of local tasks plugin definitions, keyed by plugin ID.
348  *
349  * @see \Drupal\Core\Menu\LocalTaskInterface
350  * @see \Drupal\Core\Menu\LocalTaskManager
351  *
352  * @ingroup menu
353  */
354 function hook_local_tasks_alter(&$local_tasks) {
355   // Remove a specified local task plugin.
356   unset($local_tasks['example_plugin_id']);
357 }
358
359 /**
360  * Alter contextual links before they are rendered.
361  *
362  * This hook is invoked by
363  * \Drupal\Core\Menu\ContextualLinkManager::getContextualLinkPluginsByGroup().
364  * The system-determined contextual links are passed in by reference. Additional
365  * links may be added and existing links can be altered.
366  *
367  * Each contextual link contains the following entries:
368  * - title: The localized title of the link.
369  * - route_name: The route name of the link.
370  * - route_parameters: The route parameters of the link.
371  * - localized_options: An array of URL options.
372  * - (optional) weight: The weight of the link, which is used to sort the links.
373  *
374  *
375  * @param array $links
376  *   An associative array containing contextual links for the given $group,
377  *   as described above. The array keys are used to build CSS class names for
378  *   contextual links and must therefore be unique for each set of contextual
379  *   links.
380  * @param string $group
381  *   The group of contextual links being rendered.
382  * @param array $route_parameters
383  *   The route parameters passed to each route_name of the contextual links.
384  *   For example:
385  *   @code
386  *   array('node' => $node->id())
387  *   @endcode
388  *
389  * @see \Drupal\Core\Menu\ContextualLinkManager
390  *
391  * @ingroup menu
392  */
393 function hook_contextual_links_alter(array &$links, $group, array $route_parameters) {
394   if ($group == 'menu') {
395     // Dynamically use the menu name for the title of the menu_edit contextual
396     // link.
397     $menu = \Drupal::entityManager()->getStorage('menu')->load($route_parameters['menu']);
398     $links['menu_edit']['title'] = t('Edit menu: @label', ['@label' => $menu->label()]);
399   }
400 }
401
402 /**
403  * Alter the plugin definition of contextual links.
404  *
405  * @param array $contextual_links
406  *   An array of contextual_links plugin definitions, keyed by contextual link
407  *   ID. Each entry contains the following keys:
408  *     - title: The displayed title of the link
409  *     - route_name: The route_name of the contextual link to be displayed
410  *     - group: The group under which the contextual links should be added to.
411  *       Possible values are e.g. 'node' or 'menu'.
412  *
413  * @see \Drupal\Core\Menu\ContextualLinkManager
414  *
415  * @ingroup menu
416  */
417 function hook_contextual_links_plugins_alter(array &$contextual_links) {
418   $contextual_links['menu_edit']['title'] = 'Edit the menu';
419 }
420
421 /**
422  * Perform alterations to the breadcrumb built by the BreadcrumbManager.
423  *
424  * @param \Drupal\Core\Breadcrumb\Breadcrumb $breadcrumb
425  *   A breadcrumb object returned by BreadcrumbBuilderInterface::build().
426  * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
427  *   The current route match.
428  * @param array $context
429  *   May include the following key:
430  *   - builder: the instance of
431  *     \Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface that constructed this
432  *     breadcrumb, or NULL if no builder acted based on the current attributes.
433  *
434  * @ingroup menu
435  */
436 function hook_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
437   // Add an item to the end of the breadcrumb.
438   $breadcrumb->addLink(\Drupal\Core\Link::createFromRoute(t('Text'), 'example_route_name'));
439 }
440
441 /**
442  * Alter the parameters for links.
443  *
444  * @param array $variables
445  *   An associative array of variables defining a link. The link may be either a
446  *   "route link" using \Drupal\Core\Utility\LinkGenerator::link(), which is
447  *   exposed as the 'link_generator' service or a link generated by
448  *   \Drupal\Core\Utility\LinkGeneratorInterface::generate(). If the link is a
449  *   "route link", 'route_name' will be set; otherwise, 'path' will be set.
450  *   The following keys can be altered:
451  *   - text: The link text for the anchor tag. If the hook implementation
452  *     changes this text it needs to preserve the safeness of the original text.
453  *     Using t() or \Drupal\Component\Render\FormattableMarkup with
454  *     @placeholder is recommended as this will escape the original text if
455  *     necessary. If the resulting text is not marked safe it will be escaped.
456  *   - url_is_active: Whether or not the link points to the currently active
457  *     URL.
458  *   - url: The \Drupal\Core\Url object.
459  *   - options: An associative array of additional options that will be passed
460  *     to either \Drupal\Core\Utility\UnroutedUrlAssembler::assemble() or
461  *     \Drupal\Core\Routing\UrlGenerator::generateFromRoute() to generate the
462  *     href attribute for this link, and also used when generating the link.
463  *     Defaults to an empty array. It may contain the following elements:
464  *     - 'query': An array of query key/value-pairs (without any URL-encoding) to
465  *       append to the URL.
466  *     - absolute: Whether to force the output to be an absolute link (beginning
467  *       with http:). Useful for links that will be displayed outside the site,
468  *       such as in an RSS feed. Defaults to FALSE.
469  *     - language: An optional language object. May affect the rendering of
470  *       the anchor tag, such as by adding a language prefix to the path.
471  *     - attributes: An associative array of HTML attributes to apply to the
472  *       anchor tag. If element 'class' is included, it must be an array; 'title'
473  *       must be a string; other elements are more flexible, as they just need
474  *       to work as an argument for the constructor of the class
475  *       Drupal\Core\Template\Attribute($options['attributes']).
476  *
477  * @see \Drupal\Core\Utility\UnroutedUrlAssembler::assemble()
478  * @see \Drupal\Core\Routing\UrlGenerator::generateFromRoute()
479  */
480 function hook_link_alter(&$variables) {
481   // Add a warning to the end of route links to the admin section.
482   if (isset($variables['route_name']) && strpos($variables['route_name'], 'admin') !== FALSE) {
483     $variables['text'] = t('@text (Warning!)', ['@text' => $variables['text']]);
484   }
485 }
486
487 /**
488  * @} End of "addtogroup hooks".
489  */