Latest update:
Drush core now also provide a re-save command! (since v11.0.0-rc1)
# Re-save all article entities:
drush entity:save node --bundle=article
# Re-save all shortcut entities:
drush entity:save shortcut
# Re-save nodes 22 and 24:
drush entity:save node 22,24
# Re-save all nodes except node 9, 14 and 81:
drush entity:save node --exclude=9,14,81
# Re-save all users:
drush entity:save user
# Re-save all node entities in steps of 5, defaults to 50 if omitted:
drush entity:save node --chunks=5
Update:
Aaaand some folks also created an unattributed copy of Resave All Nodes and added some more options: Save All Nodes.
Update:
I just created Resave All Nodes. For now it only contains a form and a Drush command to trigger a batch process to resave all nodes of selected node types.
For everybody coming here to find a code snippet (to be placed in MYMODULE.install
):
use \Drupal\node\Entity\Node;
/**
* Resave all pages.
*/
function MYMODULE_update_8001(&$sandbox) {
// Get an array of all 'page' node IDs.
$nids = \Drupal::entityQuery('node')
->condition('type', 'page')
->execute();
// Load all the nodes.
$nodes = Node::loadMultiple($nids);
foreach ($nodes as $node) {
$node->save();
}
}
Problem with this, of course, is you can reach your memory limit pretty fast when re-saving many thousands of nodes that way. So you have to implement a batch process.
Thankfully hook_update_N(&$sandbox)
already has this capability built-in. Follow the link for sample code.
If running your update all at once could possibly cause PHP to time
out, use the $sandbox
parameter to indicate that the Batch API should
be used for your update. In this case, your update function acts as an
implementation of callback_batch_operation()
, and $sandbox
acts as the
batch context parameter. In your function, read the state information
from the previous run from $sandbox
(or initialize), run a chunk of
updates, save the state in $sandbox
, and set $sandbox['#finished']
to
a value between 0
and 1
to indicate the percent completed, or 1
if it
is finished (you need to do this explicitly in each pass).