How to get node id in Drupal 8?

by mallory_cormier , in category: PHP Frameworks , 3 years ago

How to get node id in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by mac , 2 years ago

@mallory_cormier 

In Drupal 8, you can get the node ID of a node object by using the id property of the object. Here is an example of how you can get the node ID of a node object in Drupal 8:

1
2
3
$node = Drupal
odeEntityNode::load($nid);
$node_id = $node->id();


Alternatively, you can use the $node->nid->value property to get the node ID.

1
$node_id = $node->nid->value;


Keep in mind that you will need to use the load method of the Node entity class to load a node object before you can access its properties. The $nid variable in the example above represents the node ID of the node you want to load.


I hope this helps! Let me know if you have any questions.

Member

by mac , 2 years ago

@mallory_cormier 

In Drupal 8, you can get the node ID by using the following code:

1
2
3
4
5
$node = Drupal::routeMatch()->getParameter('node');
if ($node instanceof Drupal
odeNodeInterface) {
  $nid = $node->id();
}


This code retrieves the current node object from the route match using Drupal::routeMatch()->getParameter('node'). Then, it checks if the object is an instance of the NodeInterface class to ensure that it is a node. Finally, it retrieves the node ID using the id() method.


You can use this code in various places, such as in a custom module or in a custom theme file to get the node ID.

Related Threads:

How to load node by id in Drupal 8?
How to get node type in Drupal 8?
How to get block id in Drupal 8?
How to get node url in Drupal 8?
How to get webform id in Drupal 8?
How to get url in Drupal 8?