21.05.2026 | Michael Ebert

Do bulk updates as a batch job

custom_module.install
<?php

/**
 * Update node title of all nodes.
 */
function custom_module_update_10001(&$sandbox) {
  // Define you entity type.
  $entity_type = 'node';

  // Load the entity type manager service.
  $entity_type_manager = \Drupal::service('entity_type.manager');

  // Get the storage for the entity type.
  $entity_storage = $entity_type_manager->getStorage($entity_type);

  if (!isset($sandbox['total'])) {
    $all_entity_ids = $entity_storage->getQuery()
      ->accessCheck()
      ->execute();
    $sandbox['total'] = count($all_entity_ids);
    $sandbox['current'] = 0;

    if (empty($sandbox['total'])) {
      $sandbox['#finished'] = 1;
      return;
    }
  }

  $entities_per_batch = 25;
  $entity_ids = $entity_storage->getQuery()
    ->accessCheck()
    ->range($sandbox['current'], $entities_per_batch)
    ->execute();
  if (empty($entity_ids)) {
    $sandbox['#finished'] = 1;
    return;
  }

  // Optionally, perform operations with the loaded entities.
  // For example, load and modify each node and set a new title.
  foreach ($entity_ids as $entity_id) {
    $entity = $entity_storage->load($entity_id);

    if ($entity->hasField('title')) {
      $entity->setTitle('New Title');
    }

    $entity->save();
    $sandbox['current']++;
  }

  \Drupal::messenger()
    ->addMessage($sandbox['current'] . ' users processed.');

  if ($sandbox['current'] >= $sandbox['total']) {
    $sandbox['#finished'] = 1;
  }
  else {
    $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);
  }

}

Issue:

You have to update many entities during development and the server runs out of memory.

Solution:

Update entities in batch mode. Copy-paste the snippet code.