Last active
September 4, 2025 15:58
-
-
Save welly/bb1dfb57f0ec10541d23f9b4fea3e5e2 to your computer and use it in GitHub Desktop.
Example sandboxed post-update
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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