Skip to content

Instantly share code, notes, and snippets.

@Niklan
Last active December 17, 2020 06:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Niklan/48767c7b18112cadc2ba8423b734f718 to your computer and use it in GitHub Desktop.
Save Niklan/48767c7b18112cadc2ba8423b734f718 to your computer and use it in GitHub Desktop.
Drupal 8: Batched hook_post_update_NAME() and hook_update_N() example
<?php
/**
* @file
* Post update functions for the MYMODULE module.
*/
/**
* Summary description for an update.
*/
function mymodule_post_update_NAME(array &$sandbox) {
/** @var \Drupal\node\NodeStorageInterface $node_storage */
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
// Fetching amount of data we need to process.
// Runs only once per update.
if (!isset($sandbox['total'])) {
// This is the example of fetching amount of nodes of 'product' type.
$result_count = $node_storage
->getQuery()
->condition('type', 'product')
->count()
->execute();
// Write total of entities need to be processed to $sandbox.
$sandbox['total'] = $result_count;
// Initiate default value for current processing № of element.
$sandbox['current'] = 0;
}
// Do not continue if no entities are found.
if (empty($sandbox['total'])) {
$sandbox['#finished'] = 1;
return t('No products to be processed.');
}
// How much entities can be processed per batch.
$limit = 50;
// Fetching node id's for processing in current batch run. Make sure you are
// query the same conditions as count query.
$node_ids = $node_storage
->getQuery()
->condition('type', 'product')
->range($sandbox['current'], $limit)
->execute();
// Load entities.
$nodes = $node_storage->loadMultiple($node_ids);
/** @var \Drupal\node\NodeInterface $node */
foreach ($nodes as $node) {
// Do something to with node.
// And don't forget to save!
$node->save();
// Increment currently processed entities.
$sandbox['current']++;
}
// The batch will finish when '#finished' will become '1'.
$sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);
// Print some progress.
return t('@count products processed.', ['@count' => $sandbox['current']]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment