Your code is failing because you're putting it directly in the module file, and not using the hook system. I won't go into exactly why this won't work, if you read the Module Developer's Guide it'll make sense.
It's a bit tricky to advise what hook your code should be going in as you don't mention what you want to do with it. As an example, though, lets say you want to extract the nid
from the current page and pass it to an external service somewhere outside of Drupal.
There are several different ways to do it; at the most basic level, you could use hook_init()
, which is called on every page load. Using this method your calls to menu_get_object()
and arg()
will yield the result you're expecting:
function MODULENAME_init() {
$node = menu_get_object();
if (isset($node->nid)) {
send_data_to_external_service($node->nid);
}
}
That's all fine, but let's say you want to change the content of a node based on it's nid
. hook_init()
will be no good for this, as it has no node available to manipulate in the current context.
Instead, Drupal actually provides a hook that is called when any node in the system is prepared for view, allowing you to manipulate the content. This hook is called hook_node_view()
, and can be used like this:
function MODULENAME_node_view($node, $view_mode, $langcode) {
if ($view_mode == 'full') { // Node is being viewed on it's full node page
$node->content['my_additional_field'] = array(
'#markup' => $additional_field,
'#weight' => 10,
'#theme' => 'mymodule_my_additional_field',
);
}
}
Notice that one of the arguments that's passed to the function is the $node
object, which contains the nid
as a property. As you have this object in the current context, there's no need to query menu_get_object()
or arg()
to get the nid
.
There are dozens of different hooks in Drupal that respond to different system events, and allow your custom modules to have a say in how a page is displayed/how data is saved/etc. It might be a good exercise to read through that list and see which hooks would help with the development of your own module.
dsm()
call will likely be delayed by one page, which might give the impression it's not working.