I want to update a node field's value when a node is updated.
Tried using the code mentioned here Programmatically updating a node Drupal 8
use Drupal\node\Entity\Node;
function hello_world_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
$check = \Drupal::routeMatch()->getParameter('node');
if ($check) {
$node = Node::load($check->nid->value);
$node->title->value = 'testing'; //set value for field
$node->save();
}
}
but it did not work. I get a 500 error after saving the node. I also tried taking out the if statement and specifying a node id $node = Node::load(1);
I also tried using Update a node / Entity programmatically in Drupal 8
use Drupal\node\Entity\Node;
function hello_world_node_update(Drupal\node\NodeInterface $node) {
$node = Node::load(1);
$node->set("title", 'New value'); // also tried $node->setTitle('The new Title');
$node->save();
}
but no luck either.
In addition, I tried using different hooks entity_presave, entity_update, node_update, but did not make any difference.