Skip to content

Instantly share code, notes, and snippets.

@KeyboardCowboy
Last active April 5, 2017 18:25
Show Gist options
  • Save KeyboardCowboy/acd488f3d48ecc6f2b91 to your computer and use it in GitHub Desktop.
Save KeyboardCowboy/acd488f3d48ecc6f2b91 to your computer and use it in GitHub Desktop.
Drupal Update Hook Batch Template
<?php
/**
* Template for hook_update_N() with batching.
*/
function module_template_update_7100(&$sandbox) {
$items_per_loop = 100;
// Initial setup.
if (!isset($sandbox['processed'])) {
// Load the nids to update
$nids = db_query("select nid from {node} where type = 'TYPE'")->fetchCol();
if (empty($nids)) {
watchdog('mymodule', 'There are no items to process.', array(), WATCHDOG_NOTICE);
return;
}
$sandbox['processed'] = 0;
$sandbox['total'] = count($nids);
$sandbox['nids'] = $nids;
}
// Process a batch of nids
for ($i = 0; $i < $items_per_loop; $i++) {
if ($nid = array_shift($sandbox['nids'])) {
// Custom processing here.
}
$sandbox['processed']++;
}
// Update batch status.
$sandbox['#finished'] = ($sandbox['processed'] >= $sandbox['total']) ? 1 : ($sandbox['processed'] / $sandbox['total']);
$args = array(
'!done' => $sandbox['processed'],
'!total' => $sandbox['total'],
'!pct' => round(($sandbox['processed'] / $sandbox['total']) * 100, 2),
);
return t('Completed !done/!total (!pct%)', $args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment