Here’s how to create a node in the code directly with various field types.
First make use of the node namespace.
use Drupal\node\Entity\Node;
Simple title and body node creation : note if you don’t specify the language code, default site language will be used and same applies for the body format.
$new = Node::create([
'type' => 'content_type',
'langcode' => 'en',
'title' => "Created Programatically!",
'body' => [
'value' => "Body content TEST",
'format' => "full_html",
],
]);
Now let’s have a look for more complex fields , for instance, metatags which are stored in the database in BLOB format. Hence you will have to serialize the array before saving it.
$new->set('field_metatag', serialize([
'title' => $mt['title'],
'description' => $mt['description']['value'],
]));
Lastly let’s see for geolocation fields :
$new->set('field_map', ['lat' => '20.6514654', 'lng' => '62.065465']);
After each Node:create(), the node will not be created until you save it.
$new->save();
Please follow and like us: