Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal - Getting node id from view to customise link in block

How can I build a block in Drupal which is able to show the node ID of the view page the block is currently sitting on?

I'm using views to build a large chunk of my site, but I need to be able to make "intelligent" blocks in PHP mode which will have dynamic content depending on what the view is displaying.

How can I find the $nid which a view is currently displaying?

like image 628
MrFidge Avatar asked Nov 03 '09 17:11

MrFidge


1 Answers

Here is a more-robust way of getting the node ID:

<?php
    // Check that the current URL is for a specific node:
    if(arg(0) == 'node' && is_numeric(arg(1))) {
        return arg(1); // Return the NID
    }
    else { // Whatever it is we're looking at, it's not a node
      return NULL; // Return an invalid NID
    }
?>

This method works even if you have a custom path for your node with the path and/or pathauto modules.

Just for reference, if you don't turn on the path module, the default URLs that Drupal generates are called "system paths" in the documentation. If you do turn on the path module, you are able to set custom paths which are called "aliases" in the documentation.

Since I always have the path module turned on, one thing that confused me at first was whether it was ever possible for the arg function to return part of an alias rather than part of system path.

As it turns out, the arg function will always return a system path because the arg function is based on $_GET['q']... After a bit of research it seems that $_GET['q'] will always return a system path.

If you want to get the path from the actual page request, you need to use $_REQUEST['q']. If the path module is enabled, $_REQUEST['q'] may return either an alias or a system path.

like image 76
2 revs, 2 users 75% Avatar answered Sep 28 '22 11:09

2 revs, 2 users 75%