Update a node / Entity programmatically in Drupal 8

Question

How to update a node or an Entity programmatically in Drupal 8 ?
Update title, Update body text or other custom field;

Update a node:

Example 1 : Update title
$node = \Drupal\node\Entity\Node::load($nid);
$node->setTitle('The new Title')
$node->save();

Example 2 : Update a field ('body' and 'field_name')
$node = \Drupal\node\Entity\Node::load($nid);
$node->set("body", 'New body text');
$node->set("field_name", 'New value');
$node->save();

 

To make changes after click on save / edit button, you can use the hook_entity_presave.
hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity);
Example:
function CUSTOM_MODULE_node_presave(Drupal\node\NodeInterface $node) {
  $node->setTitle('Edited Title');
  $node->set('body', 'this is the bew body');
  //CAUTION : Do not save here, because it's automatic.
}

Note : Do not re save inside of hook_entity_presave().

Using HOOK_entity_presave()

function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityType()->id() == 'node') {
    $entity->setTitle('The new Title');
    //CAUTION : Do not save here, because it's automatic.
  }
}

 

Big thanks to this blog author

Latest blog

Web Analytics