Drupal - How to get node object from node ID

There are a few ways.

If your context allows for Dependency injection, inject the entity_type.manager service and use it like so:

$node = $this->entityTypeManager->getStorage('node')->load($nid);

If not you can still use the entity_type.manager service:

$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

If you prefer, you can use the Node class directly:

$node = \Drupal\node\Entity\Node::load($nid);

You never use new to create an entity, whenever you need to load it from the database or create it without loading it from the database.

In the case you want to create a node, you use Node::create(), as in the following example code.

  use Drupal\node\Entity\Node;

  $settings = [
    'body' => [
      [
        'value' => 'The node body is here.',
        'format' => filter_default_format(),
      ],
    ],
    'title' => 'The node title',
    'type' => 'page',
    'uid' => \Drupal::currentUser()->id(),
  ];
  $node = Node::create($settings); 

If you need to simply load a node from the database knowing its node ID, the code is much simpler.

  use Drupal\node\Entity\Node;

  $node = Node::load($nid);

If then you need to load a node from the database knowing any other properties, but not the node ID, you can use the following code.

  use Drupal\node\Entity\Node;

  $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties($values);

$nodes is an array containing zero or more nodes, and $values is an array describing the properties you know.

Tags:

Nodes

8