PageRenderTime 57ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/core/lib/Drupal/Core/Menu/menu.api.php

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