menu.api.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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_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. *
  301. * @ingroup menu
  302. */
  303. function hook_menu_local_tasks_alter(&$data, $route_name) {
  304. // Add a tab linking to node/add to all pages.
  305. $data['tabs'][0]['node.add_page'] = [
  306. '#theme' => 'menu_local_task',
  307. '#link' => [
  308. 'title' => t('Example tab'),
  309. 'url' => Url::fromRoute('node.add_page'),
  310. 'localized_options' => [
  311. 'attributes' => [
  312. 'title' => t('Add content'),
  313. ],
  314. ],
  315. ],
  316. ];
  317. }
  318. /**
  319. * Alter local actions plugins.
  320. *
  321. * @param array $local_actions
  322. * The array of local action plugin definitions, keyed by plugin ID.
  323. *
  324. * @see \Drupal\Core\Menu\LocalActionInterface
  325. * @see \Drupal\Core\Menu\LocalActionManager
  326. *
  327. * @ingroup menu
  328. */
  329. function hook_menu_local_actions_alter(&$local_actions) {
  330. }
  331. /**
  332. * Alter local tasks plugins.
  333. *
  334. * @param array $local_tasks
  335. * The array of local tasks plugin definitions, keyed by plugin ID.
  336. *
  337. * @see \Drupal\Core\Menu\LocalTaskInterface
  338. * @see \Drupal\Core\Menu\LocalTaskManager
  339. *
  340. * @ingroup menu
  341. */
  342. function hook_local_tasks_alter(&$local_tasks) {
  343. // Remove a specified local task plugin.
  344. unset($local_tasks['example_plugin_id']);
  345. }
  346. /**
  347. * Alter contextual links before they are rendered.
  348. *
  349. * This hook is invoked by
  350. * \Drupal\Core\Menu\ContextualLinkManager::getContextualLinkPluginsByGroup().
  351. * The system-determined contextual links are passed in by reference. Additional
  352. * links may be added and existing links can be altered.
  353. *
  354. * Each contextual link contains the following entries:
  355. * - title: The localized title of the link.
  356. * - route_name: The route name of the link.
  357. * - route_parameters: The route parameters of the link.
  358. * - localized_options: An array of URL options.
  359. * - (optional) weight: The weight of the link, which is used to sort the links.
  360. *
  361. *
  362. * @param array $links
  363. * An associative array containing contextual links for the given $group,
  364. * as described above. The array keys are used to build CSS class names for
  365. * contextual links and must therefore be unique for each set of contextual
  366. * links.
  367. * @param string $group
  368. * The group of contextual links being rendered.
  369. * @param array $route_parameters
  370. * The route parameters passed to each route_name of the contextual links.
  371. * For example:
  372. * @code
  373. * array('node' => $node->id())
  374. * @endcode
  375. *
  376. * @see \Drupal\Core\Menu\ContextualLinkManager
  377. *
  378. * @ingroup menu
  379. */
  380. function hook_contextual_links_alter(array &$links, $group, array $route_parameters) {
  381. if ($group == 'menu') {
  382. // Dynamically use the menu name for the title of the menu_edit contextual
  383. // link.
  384. $menu = \Drupal::entityManager()->getStorage('menu')->load($route_parameters['menu']);
  385. $links['menu_edit']['title'] = t('Edit menu: @label', ['@label' => $menu->label()]);
  386. }
  387. }
  388. /**
  389. * Alter the plugin definition of contextual links.
  390. *
  391. * @param array $contextual_links
  392. * An array of contextual_links plugin definitions, keyed by contextual link
  393. * ID. Each entry contains the following keys:
  394. * - title: The displayed title of the link
  395. * - route_name: The route_name of the contextual link to be displayed
  396. * - group: The group under which the contextual links should be added to.
  397. * Possible values are e.g. 'node' or 'menu'.
  398. *
  399. * @see \Drupal\Core\Menu\ContextualLinkManager
  400. *
  401. * @ingroup menu
  402. */
  403. function hook_contextual_links_plugins_alter(array &$contextual_links) {
  404. $contextual_links['menu_edit']['title'] = 'Edit the menu';
  405. }
  406. /**
  407. * Perform alterations to the breadcrumb built by the BreadcrumbManager.
  408. *
  409. * @param \Drupal\Core\Breadcrumb\Breadcrumb $breadcrumb
  410. * A breadcrumb object returned by BreadcrumbBuilderInterface::build().
  411. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  412. * The current route match.
  413. * @param array $context
  414. * May include the following key:
  415. * - builder: the instance of
  416. * \Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface that constructed this
  417. * breadcrumb, or NULL if no builder acted based on the current attributes.
  418. *
  419. * @ingroup menu
  420. */
  421. function hook_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
  422. // Add an item to the end of the breadcrumb.
  423. $breadcrumb->addLink(\Drupal\Core\Link::createFromRoute(t('Text'), 'example_route_name'));
  424. }
  425. /**
  426. * Alter the parameters for links.
  427. *
  428. * @param array $variables
  429. * An associative array of variables defining a link. The link may be either a
  430. * "route link" using \Drupal\Core\Utility\LinkGenerator::link(), which is
  431. * exposed as the 'link_generator' service or a link generated by
  432. * \Drupal\Core\Utility\LinkGeneratorInterface::generate(). If the link is a
  433. * "route link", 'route_name' will be set; otherwise, 'path' will be set.
  434. * The following keys can be altered:
  435. * - text: The link text for the anchor tag. If the hook implementation
  436. * changes this text it needs to preserve the safeness of the original text.
  437. * Using t() or \Drupal\Component\Utility\SafeMarkup::format() with
  438. * @placeholder is recommended as this will escape the original text if
  439. * necessary. If the resulting text is not marked safe it will be escaped.
  440. * - url_is_active: Whether or not the link points to the currently active
  441. * URL.
  442. * - url: The \Drupal\Core\Url object.
  443. * - options: An associative array of additional options that will be passed
  444. * to either \Drupal\Core\Utility\UnroutedUrlAssembler::assemble() or
  445. * \Drupal\Core\Routing\UrlGenerator::generateFromRoute() to generate the
  446. * href attribute for this link, and also used when generating the link.
  447. * Defaults to an empty array. It may contain the following elements:
  448. * - 'query': An array of query key/value-pairs (without any URL-encoding) to
  449. * append to the URL.
  450. * - absolute: Whether to force the output to be an absolute link (beginning
  451. * with http:). Useful for links that will be displayed outside the site,
  452. * such as in an RSS feed. Defaults to FALSE.
  453. * - language: An optional language object. May affect the rendering of
  454. * the anchor tag, such as by adding a language prefix to the path.
  455. * - attributes: An associative array of HTML attributes to apply to the
  456. * anchor tag. If element 'class' is included, it must be an array; 'title'
  457. * must be a string; other elements are more flexible, as they just need
  458. * to work as an argument for the constructor of the class
  459. * Drupal\Core\Template\Attribute($options['attributes']).
  460. *
  461. * @see \Drupal\Core\Utility\UnroutedUrlAssembler::assemble()
  462. * @see \Drupal\Core\Routing\UrlGenerator::generateFromRoute()
  463. */
  464. function hook_link_alter(&$variables) {
  465. // Add a warning to the end of route links to the admin section.
  466. if (isset($variables['route_name']) && strpos($variables['route_name'], 'admin') !== FALSE) {
  467. $variables['text'] = t('@text (Warning!)', ['@text' => $variables['text']]);
  468. }
  469. }
  470. /**
  471. * @} End of "addtogroup hooks".
  472. */