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.