By dman on
Am I missing a global somewhere? All I want is access to the current node, (from a block) but I can't see the best way to retrieve it.
After messing with arg(1), $q and others, I've now got:
/**
* Return the node id of the current page
* Can't find the internal hook for that, especially when aliases are in use ...
*/
function nid(){
static $nid; if(isset($nid)){return $nid;}
$q = $_REQUEST['q'];
$p = drupal_get_normal_path($q);
$nid = array_pop(explode("/",$p));
return $nid;
}
... but I'm surprised I can't see a core way to get this instead of my own function. Most modules I've looked into do something similar, all look a bit messy.
Any suggestions?
.dan.
Comments
Context is important.
In reality outside of the template functions there is no real concept of a current node that is global. Your code for example assumes that the path is node/# where # is a number. And it is true for pages that display a single node, there is a single node in the content area and the path reflects the node being viewed. Outside of that though the page maybe a list of nodes, a custom page that has nothing to do with a node.
So, if you want the block to display something based on the context of a single node you can look at the path or if you have a custom module you can use the nodeapi hook to obtain the nid of the node viewed on the page.
Hm, thanks
Yeah, I guess I hadn't considered non-node pages too much.
That'll be why my block (this is the context today) was giving odd results when showing up on the admin pages.
I AM looking at the path I think ( It's safe to assume $_REQUEST['q'] all the time? ) . I guess I should also check the first part is "node", and do is_numeric() ) on the second.
... And then I must check further to be getting the right results on 'edit' and 'preview' (which was also disappearing)
See, doing all this myself assumes too much about the internals of the way the path is built, IMO. I was hoping I wouldn't have to hard-code those rules, but I guess it explains why each (block) module had its own awkward way of doing so.
... so if there was a multiple node list on a page, I guess there's no standard way of finding out what it is/was? Just curious.
.dan.
.dan. is the New Zealand Drupal Developer working on Government Web Standards
You code write a small module
You could write a small module that implements the nodeapi hook and which some hows records the nodes viewed and then have the block use that information.
Clever thought
A tiny enumerator to count what's being viewed.
Seems the long way 'round, but definately tidy within the hook stucture, and not requiring insider knowlege.
... I don't need it today, but it's a cool concept.
.dan. is the New Zealand Drupal Developer working on Government Web Standards