Drupal 8: Programatically update Node with example

In Drupal 8, The nodes are handled as the Entity. The core class Node is helping us to manage the operations of the Node. The below is the syntax and example for update the node details. The Node updates us happens with the Node id of the particular node.

Syntax: 

use Drupal\node\Entity\Node;
 
$nodeObj = Node::load(NID); // Loading the Node by its Id.
$nodeObj->set('title', 'UPDATE_TITLE');
$nodeObj->set('FIELD_1', 'UPDATE_VALUE_1');
$nodeObj->set('FIELD_2', 'UPDATE_VALUE_2');
$nodeObj->save(); // Saving the Node object.

Example: 

use Drupal\node\Entity\Node;
 
$nodeObj = Node::load(10); // Loading the Node by its Id.
$nodeObj->set('title', 'New title updated');
$nodeObj->set('body', 'The body text has been updated');
$nodeObj->set('field_date', '2017-10-25');
$nodeObj->save(); // Saving the Node object.
Category: 

Comments

Zinahygies (not verified)
Very good post. Will read on... http://gb2m5p37.tumblr.com/ - Paup
Vijay (not verified)
About Post. Good post
Zinahygies (not verified)
Really informative forum.Much thanks again. Keep writing. http://gb2m5p37.tumblr.com/ - Velva
Zinahygies (not verified)
Wow, great article.Thanks Again. Fantastic. http://gb2m5p37.tumblr.com/ - Skalsky
codeexpertz's picture
codeexpertz
Great work