Created
August 20, 2019 06:55
-
-
Save steffenr/685b5f5b69ee475fd252bca77ad1ab86 to your computer and use it in GitHub Desktop.
Drupal 8 - Batch job in hook_update_n
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(). | |
* | |
* Set default value to new field field_registered on all Person nodes. | |
*/ | |
function MY_MODULE_update_8001(&$sandbox) { | |
// Initialize some variables during the first pass through. | |
if (!isset($sandbox['total'])) { | |
$nids = \Drupal::entityQuery('node') | |
->condition('type', 'person') | |
->execute(); | |
$sandbox['total'] = count($nids); | |
$sandbox['current'] = 0; | |
} | |
$nodes_per_batch = 25; | |
// Handle one pass through. | |
$nids = \Drupal::entityQuery('node') | |
->condition('type', 'person') | |
->range($sandbox['current'], $nodes_per_batch) | |
->execute(); | |
foreach($nids as $nid) { | |
$node = Node::load($nid); | |
$node->field_board_member->value = 0; | |
$node->save(); | |
$sandbox['current']++; | |
} | |
drupal_set_message($sandbox['current'] . ' nodes processed.'); | |
if ($sandbox['total'] == 0) { | |
$sandbox['#finished'] = 1; | |
} else { | |
$sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment