Skip to content

Instantly share code, notes, and snippets.

@JeffTomlinson
Created July 6, 2017 16:50
Show Gist options
  • Save JeffTomlinson/5621bdc4aa0976239918c1c35b3465a3 to your computer and use it in GitHub Desktop.
Save JeffTomlinson/5621bdc4aa0976239918c1c35b3465a3 to your computer and use it in GitHub Desktop.
Drupal 7 Batch Update Hook
/**
* Explanation of what this update does.
*/
function example_update_7100(&$sandbox) {
$limit = 1;
if (!isset($sandbox['processed'])) {
$nids = db_select('node', 'n')
->fields('n', array('nid'))
->condition('type', 'page', '=')
->execute()
->fetchCol();
if (empty($nids)) {
watchdog('example', 'There are no items to process.', array(), WATCHDOG_NOTICE);
return;
}
$sandbox['processed'] = 0;
$sandbox['total'] = count($nids);
$sandbox['nids'] = $nids;
}
for ($i = 0; $i < $limit; $i++) {
if ($nid = array_shift($sandbox['nids'])) {
// Do processing here.
}
$sandbox['processed']++;
}
$sandbox['#finished'] = ($sandbox['processed'] >= $sandbox['total']) ? 1 : ($sandbox['processed'] / $sandbox['total']);
$args = array(
'!processed' => $sandbox['processed'],
'!total' => $sandbox['total'],
'!pct' => round(($sandbox['processed'] / $sandbox['total']) * 100, 2),
);
return t('Completed !processed/!total (!pct%)', $args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment