Drupal - Programmatically update a field's value

You can try this code:

function MODULE_NAME_node_presave(Drupal\node\NodeInterface $node) {
  $node->setTitle('new Title');
  $node->set('body', 'this is body');
}

This is another variation with using the hook you originally tried to use.

I think the problem with your code is that you try to load a new instance of the node, but you should use the node that is provided as paramater $entity:

use Drupal\node\NodeInterface;

function hello_world_entity_presave(Drupal\Core\Entity\EntityInterface $entity)   {
  if ($entity instanceof NodeInterface) {
    $entity->title->value = 'testing';     //set value for field
    // $entity->save(); (not needed)
  }
}

Edit:

Added the use statement to the code.


Titles in Drupal 8 are not set like standard fields; they have their own function. Use $node->setTitle('New Title'); for a node or $entity->setLabel('New Title'); for a generic entity. See Node::setTitle for more info.

Tags:

8