Last active
February 25, 2022 16:11
-
-
Save vishwac09/3508c15185b88263ffa7802a3a9b8c17 to your computer and use it in GitHub Desktop.
BatchAPIHookUpdate
This file contains hidden or 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 | |
use Drupal\node\Entity\Node; | |
/** | |
* Implements hook_update_N(). | |
* Patch Content of Type article. | |
*/ | |
function xyz_update_9001(&$sandbox) { | |
// Get count only if $sandbox['max'] is not set i.e the first time. | |
if (!isset($sandbox['max'])) { | |
// Get total number of articles in the site. | |
$articlesCount = \Drupal::entityQuery('node') | |
->condition('type', 'article', '=') | |
->count() | |
->execute(); | |
} | |
// Use the sandbox to store the information needed to track progression. | |
if (!isset($sandbox['current'])) | |
{ | |
// Initialize the current count first time. | |
$sandbox['current'] = 0; | |
// Set Total number of entities first time. | |
$sandbox['max'] = $articlesCount ?? 0; | |
} | |
// Process entities in groups of 30. | |
// When a group is processed, the batch update engine determines | |
// whether it should continue processing in the same request or provide | |
// progress feedback to the user and wait for the next request. | |
// Possiblle get this value from config or environment variable. | |
$limit = 30; | |
// Limit to 30 article in one batch. | |
$articles = \Drupal::entityQuery('node') | |
->condition('type', 'article', '=') | |
->fetchAll() | |
->range($sandbox['current'], $limit) | |
->execute(); | |
foreach ($articles as $key => $value) { | |
$node = Node::load($value->uid); | |
if ($node->get('field_author') === 'XYZ') { | |
$node->set('field_publication', 'Penguin'); | |
} | |
else if ($node->get('field_author') === 'PQR') { | |
$node->set('field_publication', 'Ether'); | |
} | |
// Save the node. | |
$node->save(); | |
// Increment the number of processed nodes. | |
$sandbox['current']++; | |
// Decrement the reamining nodes count. | |
$sandbox['max']--; | |
} | |
// check if we have processed all the nodes. | |
if ($sandbox['max'] == 0) { | |
// Setting #finished >= 1, stops the batch, | |
$sandbox['#finished'] = 1; | |
} else { | |
$sandbox['#finished'] = ($sandbox['current'] / $sandbox['max']); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment