Creating entities

Programmatically creating new entities is also not rocket science and, again, we use the entity type storage handler to do so:

$values = [  'type' => 'article',  'title' => 'My title'];/** @var NodeInterface $node */$node = \Drupal::entityTypeManager()->getStorage('node')->create($values);$node->set('field_custom', 'some text');$node->save();

The storage handler has the create() method, which takes one argument in the form of an associative array of field values. The keys represent the field name and the values the value. This is where you can set initially some simpler values, and for more complex fields you still have the API we covered earlier.

If the entity type has bundles, such as the Node example given before, the bundle ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.