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%21Extensio…
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.insta…) 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!
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.