menu_example.module

  1. examples
    1. 6 menu_example/menu_example.module
    2. 7 menu_example/menu_example.module
    3. 8 menu_example/menu_example.module

Demonstrates uses of the Menu APIs in Drupal, including hook_menu(), hook_menu_alter(), and hook_menu_link_alter().

Functions & methods

NameDescription
menu_example_arg_optional_loadLoad an item based on its $id.
menu_example_arg_optional_to_argA to_arg() function is used to provide a default for the arg in the wildcard. The purpose is to provide a menu link that will function if no argument is given. For example, in the case of the menu…
menu_example_id_loadThe special _load function to load menu_example.
menu_example_menuImplementatation of hook_menu().
menu_example_menu_alterImplements hook_menu_alter().
menu_example_menu_link_alterImplements hook_menu_link_alter().
menu_example_permImplements hook_perm() to provide a demonstration access string.
menu_example_user_page_titleTitle callback to rename the title dynamically.
_menu_example_basic_instructionsPage callback for the simplest introduction menu entry.
_menu_example_mappingsUtility function to provide mappings from integers to some strings. This would normally be some database lookup to get an object or array from a key.
_menu_example_menu_pagePage callback for use with most of the menu entries. The arguments it receives determine what it outputs.
_menu_example_simple_title_callbackTitle callback to rewrite the '/user' menu link.

File

menu_example/menu_example.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Demonstrates uses of the Menu APIs in Drupal, including hook_menu(),
  5. * hook_menu_alter(), and hook_menu_link_alter().
  6. */
  7. /**
  8. * @defgroup menu_example Example: Menu API
  9. * @ingroup examples
  10. * @{
  11. * Examples using Menu API. (drupal 6)
  12. *
  13. * Demonstrates uses of the Menu APIs in Drupal, including hook_menu(),
  14. * hook_menu_alter(), and hook_menu_link_alter().
  15. *
  16. * This example is part of the Examples for Developers Project which you can download
  17. * and experiment with here: http://drupal.org/project/examples
  18. */
  19. /**
  20. * Implementatation of hook_menu().
  21. */
  22. function menu_example_menu() {
  23. // The simplest kind of menu: A simple call to a function with a menu entry.
  24. // The key of the menu item (menu_example/simplest) is the path that defines
  25. // the menu router entry.
  26. $items['menu_example'] = array(
  27. // The menu type is not required, as we're using the default.
  28. // 'type' => MENU_NORMAL_ITEM,
  29. // The title - do NOT use t() as t() is called automatically.
  30. 'title' => 'Menu Example',
  31. // Description (hover flyover for menu link). Does NOT use t(), which is
  32. // called automatically.
  33. 'description' => 'Simplest possible menu type, and the parent menu entry for others',
  34. // Function to be called when this path is accessed.
  35. 'page callback' => '_menu_example_basic_instructions',
  36. // Arguments to the page callback. Here's we'll use them just to provide
  37. // content for our page.
  38. 'page arguments' => array(t('This page is displayed by the simplest (and base) menu example. Note that the title of the page is the same as the link title. You can also <a href="!link">visit a similar page with no menu link</a>. Also, note that there is a hook_menu_alter() example that has changed the path of one of the menu items.', array('!link' => url('menu_example/path_only')))),
  39. // This is to be accessible to all users, so 'access callback' can be set
  40. // to TRUE, meaning that we should bypass all access checks.
  41. 'access callback' => TRUE,
  42. // If the page callback is located in another file, specify it here and
  43. // that file will be automatically loaded when needed.
  44. // 'file' => 'menu_example.module',
  45. // We can choose which menu gets the link. The default is 'navigation'.
  46. // 'menu_name' => 'navigation',
  47. // Show the menu link as expanded.
  48. 'expanded' => TRUE,
  49. );
  50. // Show a menu link in a menu other than the default "Navigation" menu.
  51. // The menu must already exist.
  52. $items['menu_example_alternate_menu'] = array(
  53. 'title' => 'Menu Example: Menu in alternate menu',
  54. // Machine name of the menu in which the link should appear.
  55. 'menu_name' => 'primary-links',
  56. 'page callback' => '_menu_example_menu_page',
  57. 'page arguments' => array(t('This will be in the Primary Links menu instead of the default Navigation menu')),
  58. 'access callback' => TRUE,
  59. );
  60. // A menu entry with simple permissions using user_access().
  61. // First, provide a courtesy menu item that mentions the existence of the
  62. // permissioned item.
  63. $items['menu_example/permissioned'] = array(
  64. 'title' => 'Permissioned Example',
  65. 'page callback' => '_menu_example_menu_page',
  66. 'page arguments' => array(t('A menu item that requires the "access protected menu example" permission is at <a href="!link">menu_example/permissioned/controlled</a>', array('!link' => url('menu_example/permissioned/controlled')))),
  67. 'access callback' => TRUE,
  68. 'expanded' => TRUE,
  69. );
  70. // Now provide the actual permissioned menu item.
  71. $items['menu_example/permissioned/controlled'] = array(
  72. // The title - do NOT use t() as t() is called automatically.
  73. 'title' => 'Permissioned Menu Item',
  74. 'description' => 'This menu entry will not show and the page will not be accessible without the "access protected menu example" permission.',
  75. 'page callback' => '_menu_example_menu_page',
  76. 'page arguments' => array(t('This menu entry will not show and the page will not be accessible without the "access protected menu example" permission.')),
  77. // For a permissioned menu entry, we provide an access callback which
  78. // determines whether the current user should have access. The default is
  79. // user_access(), which we'll use in this case. Since it's the default,
  80. // we don't even have to enter it.
  81. // 'access callback' => 'user_access',
  82. // The 'access arguments' are passed to the 'access callback' to help it
  83. // do its job. In the case of user_access(), we need to pass a permission
  84. // as the first argument.
  85. 'access arguments' => array('access protected menu example'),
  86. // The optional weight element tells how to order the submenu items.
  87. // Higher weights are "heavier", dropping to the bottom of the menu.
  88. 'weight' => 10,
  89. );
  90. // A menu router entry with no menu link. This could be used any time we
  91. // don't want the user to see a link in the menu. Otherwise, it's the same
  92. // as the "simplest" entry above. MENU_CALLBACK is used for all menu items
  93. // which don't need a visible menu link, including services and other pages
  94. // that may be linked to but are not intended to be accessed directly.
  95. // First, provide a courtesy link in the menu so people can find this.
  96. $items['menu_example/path_only'] = array(
  97. 'title' => 'MENU_CALLBACK example',
  98. 'page callback' => '_menu_example_menu_page',
  99. 'page arguments' => array(t('A menu entry with no menu link (MENU_CALLBACK) is at <a href="!link">!link</a>', array('!link' => url('menu_example/path_only/callback')))),
  100. 'access callback' => TRUE,
  101. 'weight' => 20,
  102. );
  103. $items['menu_example/path_only/callback'] = array(
  104. // A type of MENU_CALLBACK means leave the path completely out of the menu
  105. // links.
  106. 'type' => MENU_CALLBACK,
  107. // The title is still used for the page title, even though it's not used
  108. // for the menu link text, since there's no menu link.
  109. 'title' => 'Callback Only',
  110. 'page callback' => '_menu_example_menu_page',
  111. 'page arguments' => array(t('The menu entry for this page is of type MENU_CALLBACK, so it provides only a path but not a link in the menu links, but it is the same in every other way to the simplest example.')),
  112. 'access callback' => TRUE,
  113. );
  114. // A menu entry with tabs.
  115. // For tabs we need at least 3 things:
  116. // 1. A parent MENU_NORMAL_ITEM menu item (menu_example/tabs in this
  117. // example.)
  118. // 2. A primary tab (the one that is active when we land on the base menu).
  119. // This tab is of type MENU_DEFAULT_LOCAL_TASK.
  120. // 3. Some other menu entries for the other tabs, of type MENU_LOCAL_TASK.
  121. $items['menu_example/tabs'] = array(
  122. // 'type' => MENU_NORMAL_ITEM, // Not necessary since this is the default.
  123. 'title' => 'Tabs',
  124. 'description' => 'Shows how to create primary and secondary tabs',
  125. 'page callback' => '_menu_example_menu_page',
  126. 'page arguments' => array(t('This is the "tabs" menu entry.')),
  127. 'access callback' => TRUE,
  128. 'weight' => 30,
  129. );
  130. // For the default local task, we need very little configuration, as the
  131. // callback and other conditions are handled by the parent callback.
  132. $items['menu_example/tabs/default'] = array(
  133. 'type' => MENU_DEFAULT_LOCAL_TASK,
  134. 'title' => t('Default primary tab'),
  135. 'weight' => 1,
  136. );
  137. // Now add the rest of the tab entries.
  138. foreach(array(t('second') => 2, t('third') => 3, t('fourth') => 4) as $tabname => $weight) {
  139. $items["menu_example/tabs/$tabname"] = array(
  140. 'type' => MENU_LOCAL_TASK,
  141. 'title' => $tabname,
  142. 'page callback' => '_menu_example_menu_page',
  143. 'page arguments' => array(t('This is the tab "@tabname" in the "basic tabs" example', array('@tabname' => $tabname))),
  144. 'access callback' => TRUE,
  145. // The weight property overrides the default alphabetic ordering of menu
  146. // entries, allowing us to get our tabs in the order we want.
  147. 'weight' => $weight,
  148. );
  149. }
  150. // Finally, we'll add secondary tabs to the default tab of the tabs entry.
  151. // The default local task needs very little information.
  152. $items['menu_example/tabs/default/first'] = array(
  153. 'type' => MENU_DEFAULT_LOCAL_TASK,
  154. 'title' => t('Default secondary tab'),
  155. // The additional page callback and related items are handled by the
  156. // parent menu item.
  157. );
  158. foreach(array(t('second'), t('third')) as $tabname) {
  159. $items["menu_example/tabs/default/$tabname"] = array(
  160. 'type' => MENU_LOCAL_TASK,
  161. 'title' => $tabname,
  162. 'page callback' => '_menu_example_menu_page',
  163. 'page arguments' => array(t('This is the secondary tab "@tabname" in the "basic tabs" example "default" tab', array('@tabname' => $tabname))),
  164. 'access callback' => TRUE,
  165. );
  166. }
  167. // All the portions of the URL after the base menu are passed to the page
  168. // callback as separate arguments, and can be captured by the page callback
  169. // in its argument list. Our _menu_example_menu_page() function captures
  170. // arguments in its function signature and can output them.
  171. $items['menu_example/use_url_arguments'] = array(
  172. 'title' => 'Extra Arguments',
  173. 'description' => 'The page callback can use the arguments provided after the path used as key',
  174. 'page callback' => '_menu_example_menu_page',
  175. 'page arguments' => array(t('This page demonstrates using arguments in the path (portions of the path after "menu_example/url_arguments". For example, access it with <a href="!link1">!link1</a> or <a href="!link2">!link2</a>).', array('!link1' => url('menu_example/use_url_arguments/one/two'), '!link2' => url('menu_example/use_url_arguments/firstarg/secondarg')))),
  176. 'access callback' => TRUE,
  177. 'weight' => 40,
  178. );
  179. // The menu title can be dynamically created by using the 'title callback'
  180. // which by default is t(). Here we provide a title callback which adjusts
  181. // the menu title based on the current user's username.
  182. $items['menu_example/title_callbacks'] = array(
  183. 'title callback' => '_menu_example_simple_title_callback',
  184. 'title arguments' => array(t('Dynamic title: username=')),
  185. 'description' => 'The title of this menu item is dynamically generated',
  186. 'page callback' => '_menu_example_menu_page',
  187. 'page arguments' => array(t('The menu title is dynamically changed by the title callback')),
  188. 'access callback' => TRUE,
  189. 'weight' => 50,
  190. );
  191. // Sometimes we need to capture a specific argument within the menu path,
  192. // as with the menu entry 'menu_example/placeholder_argument/3333/display',
  193. // where we need to capture the "3333". In that case, we use a placeholder in
  194. // the path provided in the menu entry. The (odd) way this is done is by using
  195. // array(numeric_position_value) as the value for 'page arguments'. The
  196. // numeric_position_value is the zero-based index of the portion of the URL
  197. // which should be passed to the 'page callback'.
  198. // First we provide a courtesy link with information on how to access
  199. // an item with a placeholder.
  200. $items['menu_example/placeholder_argument'] = array(
  201. 'title' => 'Placeholder Arguments',
  202. 'page callback' => '_menu_example_menu_page',
  203. 'page arguments' => array(t('Demonstrate placeholders by visiting <a href="!link">menu_example/placeholder_argument/3343/display</a>', array('!link' => url('menu_example/placeholder_argument/3343/display')))),
  204. 'access callback' => TRUE,
  205. 'weight' => 60,
  206. );
  207. // Now the actual entry.
  208. $items['menu_example/placeholder_argument/%/display'] = array(
  209. 'title' => 'Placeholder Arguments',
  210. 'page callback' => '_menu_example_menu_page',
  211. // Pass the value of '%', which is zero-based argument 2, to the
  212. // 'page callback'. So if the URL is
  213. // 'menu_example/placeholder_argument/333/display' then the value 333
  214. // will be passed into the 'page callback'.
  215. 'page arguments' => array(2),
  216. 'access callback' => TRUE,
  217. );
  218. // Drupal provides magic placeholder processing as well, so if the placeholder
  219. // is '%menu_example_arg_optional', the function
  220. // menu_example_arg_optional_load($arg) will be called to translate the path
  221. // argument to a more substantial object. $arg will be the value of the
  222. // placeholder. Then the return value of menu_example_id_load($arg) will be
  223. // passed to the 'page callback'.
  224. // In addition, if (in this case) menu_example_arg_optional_to_arg() exists,
  225. // then a menu link can be created using the results of that function as a
  226. // default for %menu_example_arg_optional.
  227. $items['menu_example/default_arg/%menu_example_arg_optional'] = array(
  228. 'title' => 'Processed Placeholder Arguments',
  229. 'page callback' => '_menu_example_menu_page',
  230. 'page arguments' => array(2), // arg 2 (3rd arg) is the one we want.
  231. 'access callback' => TRUE,
  232. 'weight' => 70,
  233. );
  234. $items['menu_example/menu_original_path'] = array(
  235. 'title' => 'Menu path that will be altered by hook_menu_alter()',
  236. 'page callback' => '_menu_example_menu_page',
  237. 'page arguments' => array(t('This menu item was created strictly to allow the hook_menu_alter() function to have something to operate on. hook_menu defined the path as menu_example/menu_original_path. The hook_menu_alter() changes it to menu_example/menu_altered_path. You can try navigating to both paths and see what happens!')),
  238. 'access callback' => TRUE,
  239. 'weight' => 80,
  240. );
  241. return $items;
  242. }
  243. /**
  244. * Page callback for the simplest introduction menu entry.
  245. *
  246. * @param $content
  247. * Some content passed in.
  248. */
  249. function _menu_example_basic_instructions($content = NULL) {
  250. $base_content = t(
  251. 'This is the base page of the Menu Example. There are a number of examples
  252. here, from the most basic (like this one) to extravagant mappings of loaded
  253. placeholder arguments. Enjoy!');
  254. return '<div>' . $base_content . '</div><br /><div>' . $content . '</div>';
  255. }
  256. /**
  257. * Page callback for use with most of the menu entries. The arguments it
  258. * receives determine what it outputs.
  259. *
  260. * @param $content
  261. * The base content to output.
  262. * @param $arg1
  263. * First additional argument from the path used to access the menu
  264. * @param $arg2
  265. * Second additional argument.
  266. */
  267. function _menu_example_menu_page($content = NULL, $arg1 = NULL, $arg2 = NULL) {
  268. $output = '<div>' . $content . '</div>';
  269. if (!empty($arg1)) {
  270. $output .= '<div>' . t('Argument 1=%arg', array('%arg' => $arg1)) . '</div>';
  271. }
  272. if (!empty($arg2)) {
  273. $output .= '<div>' . t('Argument 2=%arg', array('%arg' => $arg2)) . '</div>';
  274. }
  275. return $output;
  276. }
  277. /**
  278. * Implements hook_perm() to provide a demonstration access string.
  279. */
  280. function menu_example_perm() {
  281. return array('access protected menu example');
  282. }
  283. /**
  284. * Utility function to provide mappings from integers to some strings.
  285. * This would normally be some database lookup to get an object or array from
  286. * a key.
  287. *
  288. * @param $id
  289. *
  290. * @return
  291. * The string to which the integer key mapped, or NULL if it did not map.
  292. */
  293. function _menu_example_mappings($id) {
  294. $mapped_value = NULL;
  295. static $mappings = array(
  296. 1 => 'one',
  297. 2 => 'two',
  298. 3 => 'three',
  299. 99 => 'jackpot! default',
  300. );
  301. if (isset($mappings[$id])) {
  302. $mapped_value = $mappings[$id];
  303. }
  304. return $mapped_value;
  305. }
  306. /**
  307. * The special _load function to load menu_example.
  308. *
  309. * Given an integer $id, load the string that should be associated with it.
  310. * Normally this load function would return an array or object with more
  311. * information.
  312. *
  313. * @param $id
  314. * The integer to load.
  315. *
  316. * @return
  317. * A string loaded from the integer.
  318. */
  319. function menu_example_id_load($id) {
  320. // Just map a magic value here. Normally this would load some more complex
  321. // object from the database or other context.
  322. $mapped_value = _menu_example_mappings($id);
  323. if (!empty($mapped_value)) {
  324. return t('Loaded value was %loaded', array('%loaded' => $mapped_value));
  325. }
  326. else {
  327. return t('Sorry, the id %id was not found to be loaded', array('%id' => $id));
  328. }
  329. }
  330. /**
  331. * Implements hook_menu_alter().
  332. *
  333. * Changes the path 'menu_example/menu_original_path' to 'menu_example/menu_altered_path'.
  334. * Changes the title callback of the 'user/UID' menu item.
  335. *
  336. * Remember that hook_menu_alter() only runs at menu_rebuild() time, not every
  337. * time the page is built, so this typically happens only at cache clear time.
  338. *
  339. * @param $items
  340. * The complete list of menu router items ready to be written to the
  341. * menu_router table.
  342. */
  343. function menu_example_menu_alter(&$items) {
  344. // Change the path 'menu_example/menu_original_path' to 'menu_example/menu_altered_path'. This change will
  345. // prevent the page from appearing at the original path (since the item is being unset).
  346. // You will need to go to menu_example/menu_altered_path manually to see the page.
  347. if (!empty($items['menu_example/menu_original_path'])) {
  348. $items['menu_example/menu_altered_path'] = $items['menu_example/menu_original_path'];
  349. $items['menu_example/menu_altered_path']['title'] = 'Menu item altered by hook_menu_alter()';
  350. unset($items['menu_example/menu_original_path']);
  351. }
  352. // Here we will change the title callback to our own function, changing the
  353. // 'user' link from the traditional to always being "username's account".
  354. if (!empty($items['user/%user_uid_optional'])) {
  355. $items['user/%user_uid_optional']['title callback'] = 'menu_example_user_page_title';
  356. }
  357. }
  358. /**
  359. * Title callback to rewrite the '/user' menu link.
  360. *
  361. * @param $base_string
  362. * string to be prepended to current user's name.
  363. */
  364. function _menu_example_simple_title_callback($base_string) {
  365. global $user;
  366. $username = !empty($user->name) ? $user->name : t('anonymous');
  367. return $base_string . ' ' . $username;
  368. }
  369. /**
  370. * Title callback to rename the title dynamically.
  371. *
  372. * @param $account
  373. * User account related to the visited page.
  374. */
  375. function menu_example_user_page_title($account) {
  376. return t("@name's account", array('@name' => $account->name));
  377. }
  378. /**
  379. * Implements hook_menu_link_alter().
  380. *
  381. * This code will get the chance to alter a menu link when it is being saved
  382. * in the menu interface at admin/build/menu. Whatever we do here overrides
  383. * anything the user/administrator might have been trying to do.
  384. *
  385. * @param $item
  386. * The menu item being saved.
  387. * @param $menu
  388. * The entire menu router table.
  389. */
  390. function menu_example_menu_link_alter(&$item, $menu) {
  391. // Force the link title to remain 'Clear Cache' no matter what the admin
  392. // does with the web interface.
  393. if ($item['link_path'] == 'devel/cache/clear') {
  394. $item['link_title'] = 'Clear Cache';
  395. };
  396. }
  397. /**
  398. * Load an item based on its $id.
  399. *
  400. * In this case we're just creating a more extensive string. In a real example
  401. * we would load or create some type of object.
  402. *
  403. * @param $id
  404. */
  405. function menu_example_arg_optional_load($id) {
  406. $mapped_value = _menu_example_mappings($id);
  407. if (!empty($mapped_value)) {
  408. return t('Loaded value was %loaded', array('%loaded' => $mapped_value));
  409. }
  410. else {
  411. return t('Sorry, the id %id was not found to be loaded', array('%id' => $id));
  412. }
  413. }
  414. /**
  415. * A to_arg() function is used to provide a default for the arg in the
  416. * wildcard. The purpose is to provide a menu link that will function if no
  417. * argument is given. For example, in the case of the menu item
  418. * 'menu_example/default_arg/%menu_example_arg_optional' the third argument
  419. * is required, and the menu system cannot make a menu link using this path
  420. * since it contains a placeholder. However, when the to_arg() function is
  421. * provided, the menu system will create a menu link pointing to the path
  422. * which would be created with the to_arg() function filling in the
  423. * %menu_example_arg_optional.
  424. *
  425. * @param $arg
  426. * The arg (URL fragment) to be tested.
  427. */
  428. function menu_example_arg_optional_to_arg($arg) {
  429. // If our argument is not provided, give a default of 99.
  430. return (empty($arg) || $arg == '%') ? 99 : $arg;
  431. }
  432. /**
  433. * @} End of "defgroup menu_example".
  434. */
Login or register to post comments