0

I'd like to do something with menu links when they are saved.

I can use hook_menu_link_alter():

function my_module_menu_link_alter($item) {
  my_module_do_something($item);
}

This seems like the best and only hook I can use here. Only, the my_module_do_something function requires $item to have the mlid propety (menu link ID) set, and when a new item is being saved, the property doesn't exist yet.

I can fake it by querying the database for the most recent mlid value and incrementing 1:

$item['mlid'] = db_query('SELECT mlid FROM {menu_links} ORDER BY mlid DESC LIMIT 1')->fetchField() + 1;

(I'm not sure if I can use MAX() here, I don't know enough about dbs that aren't MySQL or Postgres)

And I think this will work fine for my specific use case, but I'm curious to know if there is a better, more generic solution. It seems to me that this one will break down if content is being imported rapidly while users are active on the site, for example.

What is the best way to pass the future value of the item's mlid property to my function?

  • 1
    There's no reliable way to do it, you're asking to predict an unpredictable future. If a menu link is added, then deleted, your method will immediately fail as the auto increment won't reset itself. In that case you'd need max() +2, then max() +3 when it happens again, and so on. I'd recommend finding a different solution to this, what you have at the moment is doomed to failure unfortunately. If something you're doing requires the mlid, then you need to use the update or insert hook (api.drupal.org/api/drupal/7/search/hook_menu_link) – Clive Jan 17 '15 at 10:42
  • ! I didn't even see hook_menu_link_insert because I was looking in menu.inc, and didn't read to the bottom of menu_link_save(). Thanks for the pointer, and the tip to use search. – calebtr Jan 18 '15 at 7:30
0

As Clive points out, the best way to do pass a menu link ID (mlid) when a menu item is created or updated is to use hook_menu_link_insert(), hook_menu_link_update() and hook_menu_link_delete() instead of hook_menu_link_alter().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.