11

in a drupal 8 custom module, how do I get a node object if I have the node id? I tried :

$node = new Node($nid);
$node->save();`

but got this error:

Argument 1 passed to Drupal\Core\Entity\ContentEntityBase::__construct() must be of the type array, string given,

2 Answers 2

32

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);
6

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.