Following is the code where I'm willing to update the description
of the field_meta_tags
of all my products using the batch process.
It's getting executed & working as expected, but only for the first batch.
function mymodule_update_8001($sandbox) {
if (!isset($sandbox['total'])) {
$products = \Drupal::entityQuery('commerce_product')
->condition('type', 'default')
->execute();
$sandbox['total'] = count($products);
$sandbox['current'] = 0;
}
$products_per_batch = 25;
$products = \Drupal::entityQuery('commerce_product')
->condition('type', 'default')
->range($sandbox['current'], $sandbox['current'] + $products_per_batch)
->execute();
foreach ($products as $product_id) {
$product = Drupal\commerce_product\Entity\Product::load($product_id);
$product->set('field_meta_tags', serialize(['description' => '']));
$product->save();
$sandbox['current']++;
}
\Drupal::messenger()
->addMessage($sandbox['current'] . ' products processed.');
$sandbox['#finished'] = empty($sandbox['total']) ? 1 : ($sandbox['current'] / $sandbox['total']);
}
Once the above hook_update_n($sandbox)
is executed, getting the following output at the terminal:
--------------- ----------- --------------- -------------
Module Update ID Type Description
--------------- ----------- --------------- -------------
mymodule 8001 hook_update_n Updates.
--------------- ----------- --------------- -------------
// Do you wish to run the specified pending updates?: yes.
> [notice] Update started: mymodule_update_8001
> [notice] Update completed: mymodule_update_8001
> [notice] Message: 25 products processed.
>
[success] Finished performing updates.
Not sure how $sandbox['#finished']
is getting the value as 1, since that's how I remember we ask the batch to stop processing.
hook_update_N
implementations can act as batch callbacks (and thus invoked multiple times in the same update script). There's a note on it in the docsfunction mymodule_update_8001(&$sandbox)
, as arrays have weird pass by value/reference rules in PHP. So, I highly suspect in the UpdateManager(?), this isn't actually being called as a batch.