0

I want to learn to alter node fields after a migration. I have a custom module and inside is a .inc file I use as a script that I will run once using drush eval module_load_include. I want to learn a simple task like replacing text inside all nodes body field. First I load all nodes, then search the body fields for all nodes for the word "red" than I want to replace that word with "blue" How would I write this? This is my starting point

<?php

use Drupal\Component\Utility\Html;
use \Drupal\node\Entity\Node;

function _update_node() {

// load nodes  
foreach($nids as $nid) {
    $node = Node::load($nid);

// do the work  here

  $node->save();

}

Then I want to run this script once. My module name is create_content. So I can run the command.

drush eval "module_load_include('inc', 'create_content', 'create_content'); _update_node();" > debug.txt

1 Answer 1

2

Here is how to update body field :

$nodes = Node::loadMultiple();
foreach($nodes as $node){
  $html = $node->body->value;
  $html = str_replace('blue','red',$html);  
  $node->set('body', [
          'summary' => 'the summary',
          'value' => $html,
          'format' => 'full_html', // probably, 
          /**
           * Correspond with format you need in admin/config/content/formats
           */
   ]);
   $node->save();
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.