Example of batched update some entities with hook_post_update_NAME() or hook_update_N().
Last active
December 17, 2020 06:50
-
-
Save Niklan/48767c7b18112cadc2ba8423b734f718 to your computer and use it in GitHub Desktop.
Drupal 8: Batched hook_post_update_NAME() and hook_update_N() example
This file contains 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 | |
/** | |
* @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