Re-save all nodes of a particular type in an update hook in Drupal 8

I recently needed to re-save all the nodes of a particular content type (after I had added some fields and default configuration) as part of a Drupal 8 site update and deployment. I could go in after deploying the new code and configuration, and manually re-save all content using the built-in bulk operation available on the /admin/content page, but that would not be ideal, because there would be a period of time where the content isn't updated on the live site—plus, manual processes are fragile and prone to failure, so I avoid them at all costs.

In my Drupal 8 module, called custom, I added the following update hook, inside custom.install:

<?php
// Add this line at the top of the .install file.
use Drupal\node\Entity\Node;

/**
 * Re-save all Article content.
 */
function custom_update_8002() {
 
// Get an array of all 'article' node ids.
 
$article_nids = \Drupal::entityQuery('node')
    ->
condition('type', 'article')
    ->
execute();

 
// Load all the articles.
 
$articles = Node::loadMultiple($article_nids);
  foreach (
$articles as $article) {
   
$article->save();
  }
}
?>

Though Drupal 8's configuration management system allows almost any config changes to be made without update hooks nowadays... I find I still need to use update hooks on many sites to deploy updates that affect the way a theme or a view displays content on the site (especially when adding new fields to existing content types).

Comments

Thanks for sharing! If your site has a lot of nodes you might find you'll run out of memory or hit a PHP timeout with the code as it stands. The hook_update_N function takes an argument called $sandbox which allows you to run the update in batches in such a situation to prevent this. There is an example on the API page: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension...

Hope you don't have too many articles on that site! If you do, using the batch API will help keep things manageable - system_update_8002() (http://cgit.drupalcode.org/drupal/tree/core/modules/system/system.instal...) is a good example of how to do this.

Ah, quite right! In this case, early in the build, we only have a couple hundred articles, so it's not a big deal. But for many cases, where you have hundreds, thousands, or more, batching the process is a necessity!