Skip to content

Instantly share code, notes, and snippets.

@prasadshir
Last active May 9, 2020 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save prasadshir/656bbc57269a4a24bbd24d6015e55d92 to your computer and use it in GitHub Desktop.
Save prasadshir/656bbc57269a4a24bbd24d6015e55d92 to your computer and use it in GitHub Desktop.
D728: Task-06 Update nodes programatically
<?php
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');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment