function NodeBulkUpdate::process

Updates all nodes in the passed-in array with the passed-in field values.

IMPORTANT NOTE: This function is intended to work when called from a form submission handler. Calling it outside of the form submission process may not work correctly.

Parameters

array $nodes: Array of node nids or nodes to update.

array $updates: Array of key/value pairs with node field names and the value to update that field to.

string|null $langcode: (optional) The language updates should be applied to. If NULL all available languages are processed.

bool $load: (optional) TRUE if $nodes contains an array of node IDs to be loaded, FALSE if it contains fully loaded nodes. Defaults to FALSE.

bool $revisions: (optional) TRUE if $nodes contains an array of revision IDs instead of node IDs. Defaults to FALSE; will be ignored if $load is FALSE.

File

core/modules/node/src/NodeBulkUpdate.php, line 46

Class

NodeBulkUpdate
Provides a service to update nodes in bulk.

Namespace

Drupal\node

Code

public function process(array $nodes, array $updates, ?string $langcode = NULL, bool $load = FALSE, bool $revisions = FALSE) : void {
  // We use batch processing to prevent timeout when updating a large number
  // of nodes.
  if (count($nodes) > 10) {
    $batch_builder = (new BatchBuilder())->addOperation([
      static::class,
      'batchProcess',
    ], [
      $nodes,
      $updates,
      $langcode,
      $load,
      $revisions,
    ])
      ->setFinishCallback([
      static::class,
      'batchFinished',
    ])
      ->setTitle($this->t('Processing'))
      ->setErrorMessage($this->t('The update has encountered an error.'))
      ->setProgressMessage('');
    batch_set($batch_builder->toArray());
  }
  else {
    /** @var \Drupal\node\NodeStorageInterface $storage */
    $storage = $this->entityTypeManager
      ->getStorage('node');
    if ($load) {
      $nodes = $revisions ? $storage->loadMultipleRevisions($nodes) : $storage->loadMultiple($nodes);
    }
    foreach ($nodes as $node) {
      static::processNode($node, $updates, $langcode);
    }
    $this->messenger
      ->addStatus($this->t('The update has been performed.'));
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.