menu_example.module

Tracking 7.x-1.x branch
  1. drupal
    1. 6 contributions/examples/menu_example/menu_example.module
    2. 7 contributions/examples/menu_example/menu_example.module
    3. 8 contributions/examples/menu_example/menu_example.module

Module file for menu_example.

Functions & methods

NameDescription
menu_example_arg_optional_loadLoads 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_custom_accessDetermine whether the current user has the role specified.
menu_example_id_loadThe special _load function to load menu_example.
menu_example_menuImplements hook_menu().
menu_example_menu_alterImplements hook_menu_alter().
menu_example_menu_link_alterImplements hook_menu_link_alter().
menu_example_permission
menu_example_user_page_titleTitle callback to rename the title dynamically, based on user_page_title().
_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

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