Update nodes programmatically

Tutorial Goal

Lesson Goal:

Implementation Method

D7

D8

node_load(), node_save()

hook_ENTITY_TYPE_update()

$node->set()

D7 Code

Add the following in lotus.module file

/**
 * Implements hook_user_update().
 * If a user has a Role named 'moderated',
 * append the words 'MODERATED USER' to titles of
 * all the nodes authored by the user
 */

function lotus_user_update(&$edit, $account, $category){
  $uid = $account->uid;
  $role = user_has_role('moderated', $account); 
  if($role){
    $query = new EntityFieldQuery();
    $query = $query
          ->entityCondition('entity_type', 'node')
          ->propertyCondition('status', 1)
          ->propertyCondition('uid', $uid);
    $nodes = $query->execute();

    foreach($nodes as $node) {
      $node = node_load($node);
      $old_title = $node->title;
      if(strpos($old_title,'(MODERATED USER)') == FALSE) {
        $node->title =  $old_title . " (MODERATED USER)";
        $node->save();
      }
    }
    drupal_set_message('All nodes of the user updated');
  }
}

D8 Code

1. Create a role named Moderated on your site (machine name moderated)

2. Add a user

3. Create some nodes and set the Author as the newly added user

4. In lotus.module, add the following code:

use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;

/**
 * Implements hook_ENTITY_TYPE_update().
 * If a user has a Role named 'moderated',
 * append the words 'MODERATED USER' to titles of
 * all the nodes authored by the user
 */

function lotus_user_update(\Drupal\Core\Entity\EntityInterface $entity){
  $user = User::load($entity->id());
  $role = $user->hasRole('moderated');
  if($role){
    $query = \Drupal::entityQuery('node')
      ->condition('uid', $user->id());
    $nids = $query->execute();
    $nodes = Node::loadMultiple($nids);
    foreach($nodes as $node) {
      $old_title = $node->title->value;
      if(strpos($old_title,'(MODERATED USER)') == FALSE) {
        $node->set("title",  $old_title . " (MODERATED USER)");
        $node->save();

      }
    }
    drupal_set_message('All nodes of the user updated');
  }
}

5. Enable the Lotus module (if its already enabled, do a Cache Rebuild)

6. Go go People, edit the user and add Moderated role to the user

7. All the nodes created by the user should be appended with the words (Moderated User)

Gist Link

https://gist.github.com/prasadshir/656bbc57269a4a24bbd24d6015e55d92

 

Contact supportStill need assistance? Contact Acquia Support