mstef
mstef

Reputation: 1194

Help for custom menu

Drupal 7 hook_menu() is confusing me; I have tried everything and I can't seem to get this to work.

What I need: In a custom module, I'd like to create a new menu, and add about four links to that menu. It sounds simple, but I am struggling. I've been able to create the menu itself using the $menu array in the .install file, but adding items to that menu doesn't make sense.

Code that is working:

$menu = array(
  'menu_name' => 'project-menu', 
  'title' => $t('Project Menu'), 
  'description' => 'Project Menu',
); 

menu_save($menu);

Code that isn't working:

$items = array();

$items['project-menu/%'] = array(
  'title' => 'Test Link',
  'page callback' => 'dc_project_page',
  'page arguments' => array(1),
  'access callback' => TRUE,
  'type' => MENU_LOCAL_TASK,
);

return $items;

This is all in the dc_project.install file under the dc_project_menu() function. Hopefully I'm just doing something stupid, any and all help is extremely appreciated. Even just pointing to me to a module that does this cleanly as an example, thanks. I did look at the example project, haven't been able to get anything as far as adding links to my new menu working.

Upvotes: 2

Views: 640

Answers (1)

avpaderno
avpaderno

Reputation: 29669

Passing to menu_save() the content of $items doesn't work because menu_save() accepts only an array containing menu_name, title, and description. What you use in $items is an array describing the menu callbacks implemented by a module, and the definitions of the menu callbacks implemented by all the modules are not saved in "menu_custom" (the table used from menu_save()) but are cached in a Drupal cache table.

If you are trying to change the menu callbacks defined by another module, then you should implement hook_menu_alter(); otherwise, if you just want do define the menu callbacks of your module, you should implement hook_menu().

Both the hooks implementations (hook_menu() and hook_menu_alter()) must be in the module file (in your case, in dc_project.module), not in dc_project.install. Drupal doesn't load the installation file when it normally loads the enabled modules; it loads the installation file when a module is being updated (or installed), but it doesn't load it in other cases.
The code that saves the menu with menu_save() can be in the installation file, in the implementation of hook_install() or hook_update_N(). It could also be put in the implementation of hook_enable(); in that case, the code (which is executed when the module is enabled) should first verify the menu has not been already added. (hook_enable() and hook_disable() should be placed in the installation file.)

Upvotes: 2

Related Questions