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 \Drupal\node\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 above, the bundle needs to be specified in the create() method. The key it corresponds to is the entity key for the bundle. If you remember the Node entity type plugin, that is type.

That is pretty much it. Again, we need to save it in order to persist it in our storage.