Programmatically update a node field’s value in Drupal 8

0
2435
Programmatically update a node field's value in Drupal 8
Programmatically update a node field's value in Drupal 8

In this post, I will show you a tip to programmatically update a node field’s value in Drupal 8.

To update a node field’s value, we will make use of node_presave() hook. Let say we want to update title, body and custom field like group, this is how we implement the hook:

function MODULE_node_presave(Drupal\node\NodeInterface $node) {
    $node->setTitle('A New Title');
    $node->set('body', 'This is the updated body content');
    $node->set('field_group', 12);
}

Another hook we can also use is entity_presave():

use Drupal\node\NodeInterface;

function MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity)   {
  if ($entity instanceof NodeInterface) {
    $entity->set('title', 'A New Title');
    $entity->set('body', 'This is the updated body content');
    $entity->set('field_group', 12);
  }
}

That’s how to programmatically update a node field’s value in Drupal 8.

Have fun!