menu.api.php 20 KB

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