Skip to main content
Category:

Simple snippet on how to update node fields programmatically in drupal 8.

Fisrt import Node entity: 

use Drupal\node\Entity\Node;

Then use below code inside a function where you want to update the nodes.

/**
 * hook_cron(): called every time the Drupal cron runs
 */
function mymodule_cron()
{
  $query = \Drupal::entityQuery('node')
    ->condition('nid', '1');
  $nids = $query->execute();
  $nodes = Node::loadMultiple($nids);
  foreach ($nodes as $node) {
    $node->set("title", strtoupper($node->title->value));
    $node->save();
  }
  \Drupal::messenger()->addMessage('Nodes updated');
}

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook