Accessing the current node ID in Drupal

 

From time to time you just need the node ID of the current node to get things done. In Drupal 7 you simply used the arg() function to do this, this approach no longer works for Drupal 8 and onwards because arg() is deprecated.

Published on September 23, 2020

The main reason for the global arg() function to be deprecated in Drupal 8 and onwards is that it no longer served any specific need. Besides that, using the arg() function needed some extra care to avoid getting unexpected results. Say that you wanted to load a node on the path 'article/123', executing arg(1) would return '123' with which you could load the node. Using the '123' returned by arg(1) did not in any way guarantee that the path was valid or even that a node with ID 123 existed.

In Drupal 8 and onwards things are done differently. Consider the following:

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  $nid = $node->id();
  // Do whatever you need to do with the node ID here...
}

Getting the node ID this way is far more robust than doing so the old way using the arg() function. We know for sure the node exists and the path is valid because routeMatch() would not return a node object otherwise. As a bonus you can easily do some extra validation because you already have the node object loaded. You could, for instance, check that the node is of type 'article' by adding:

if ($node->bundle() == 'article') {

Getting the node ID this way may seem like a lot more work than using the deprecated arg() function, but it certainly guarantees a way more robust way of working which in turn will make your code better and more stable.

___

Need help developing your Drupal website? Our team of expert Drupal developers would be more than happy to help you out!

planet drupal
drupal
drupal 8
drupal 9