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:

// 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')

// Load all the articles.
$articles = Node::loadMultiple($article_nids);
  foreach (
$articles as $article) {

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).


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!

You need to check your css. Black on gray or blue on grey barely to not readable. I will try with install, from the admin interface same code runs into timeout.

I'm assuming you're talking about the code example in this post, if you have dark mode enabled on your computer. The problem is Drupal's code syntax highlighting plugin has defaults that only really work for light mode / light backgrounds, and I haven't had time to override the defaults so they don't screw up eyesight in dark mode.

This only happens when I put in PHP examples (e.g. <\?php \?>), which I rarely do anymore.