n Updating nodes programmatically in Drupal | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

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));
  \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


Page Facebook