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
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');
}
Tags :

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon