Reputation: 9910
I am developing a new module and in my hook_menu_alter() I need to detect the node currently being viewed.
Instead of using arg(1)
to fetch the the node id from the url, I discovered I can use
menu_get_object().
The following code works in my hook_init() but does not in hook_menu_alter():
$node = menu_get_object();
dpm($node);
Can anyone offer some insight into why that does not work and how to get the current node infomation in hook_menu_alter()?
Thanks.
Upvotes: 1
Views: 973
Reputation: 36956
The output from hook_menu
, hook_menu_alter
etc. is cached so those functions will only be called when the caches are cleared, not for every page load. If you think about, if the menus were rebuilt on every page load the performance of the site would suffer considerably.
As such, when hook_menu_alter
is called (which won't be from a node page), there's no node for menu_get_object()
to give you. The way to handle these things is in the page/access callback for the menu item:
function mymodule_menu_alter(&$items) {
$items['some/path']['page callback'] = 'mymodule_page_callback';
}
function mymodule_page_callback() {
// This is a live page so menu_get_object() is now available
$node = menu_get_object();
}
From your comment I think you're trying to deny access to particular nodes based on some criteria. For this you'll want to implement your own access callback for the already existing node/%
menu path. Something like this:
function mymodule_menu_alter(&$items) {
$items['node/%node']['access callback'] = 'mymodule_access_callback';
}
function mymodule_access_callback($node) {
if ($node->type == 'group') {
if (some_function_that_determines_access($node)) {
return TRUE;
}
return FALSE;
}
return node_access('view', $node);
}
Upvotes: 2