Skip to content

Instantly share code, notes, and snippets.

@welly
Last active September 4, 2025 15:58
Show Gist options
  • Save welly/bb1dfb57f0ec10541d23f9b4fea3e5e2 to your computer and use it in GitHub Desktop.
Save welly/bb1dfb57f0ec10541d23f9b4fea3e5e2 to your computer and use it in GitHub Desktop.
Example sandboxed post-update
<?php
/**
* Example sandboxed post-update.
*
* This shows the basic structure you can copy for long-running updates.
*/
function mymodule_post_update_example_sandbox(&$sandbox) {
// 1. Initialisation (first run).
if (!isset($sandbox['initialised'])) {
$sandbox['initialised'] = TRUE;
// Gather all entity IDs you want to process.
$sandbox['nids'] = \Drupal::entityQuery('node')
->accessCheck(FALSE)
->execute();
$sandbox['total'] = count($sandbox['nids']); // Total items.
$sandbox['processed'] = 0; // Counter.
}
// 2. Exit early if no work to do.
if (empty($sandbox['nids'])) {
$sandbox['#finished'] = 1;
return t('No nodes to process.');
}
// 3. Work in chunks (avoid timeouts).
$limit = 50;
$nids_chunk = array_splice($sandbox['nids'], 0, $limit);
// Load and process entities.
$nodes = \Drupal::entityTypeManager()
->getStorage('node')
->loadMultiple($nids_chunk);
foreach ($nodes as $node) {
// Do your real work here — e.g. update fields, save, etc.
// For demo purposes we’ll just mark as processed.
// $node->set('field_example', 'some value');
// $node->save();
$sandbox['processed']++;
}
// 4. Tell Drupal how far we are.
$sandbox['#finished'] = $sandbox['processed'] / max(1, $sandbox['total']);
// 5. Return a status message that appears in Drush output.
return t('Processed @done of @total nodes.', [
'@done' => $sandbox['processed'],
'@total' => $sandbox['total'],
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment