Batch operations

Same name in other branches
  1. 7.x includes/form.inc \batch
  2. 9 core/includes/form.inc \batch
  3. 8.9.x core/includes/form.inc \batch
  4. 10 core/includes/form.inc \batch

Creates and processes batch operations.

Functions allowing forms processing to be spread out over several page requests, thus ensuring that the processing does not get interrupted because of a PHP timeout, while allowing the user to receive feedback on the progress of the ongoing operations.

The API is primarily designed to integrate nicely with the Form API workflow, but can also be used by non-Form API scripts (like update.php) or even simple page callbacks (which should probably be used sparingly).

Example:

$batch = [
    'title' => t('Exporting'),
    'operations' => [
        [
            'my_function_1',
            [
                $account->id(),
                'story',
            ],
        ],
        [
            'my_function_2',
            [],
        ],
    ],
    'finished' => 'my_finished_callback',
    'file' => 'path_to_file_containing_my_functions',
];
batch_set($batch);
// Only needed if not inside a form _submit handler.
// Setting redirect in batch_process.
batch_process('node/1');

Note: if the batch 'title', 'init_message', 'progress_message', or 'error_message' could contain any user input, it is the responsibility of the code calling batch_set() to sanitize them first with a function like \Drupal\Component\Utility\Html::escape() or \Drupal\Component\Utility\Xss::filter(). Furthermore, if the batch operation returns any user input in the 'results' or 'message' keys of $context, it must also sanitize them first.

Sample callback_batch_operation():

// Simple and artificial: load a node of a given type for a given user
function my_function_1($uid, $type, &$context) {
    // The $context array gathers batch context information about the execution (read),
    // as well as 'return values' for the current operation (write)
    // The following keys are provided :
    // 'results' (read / write): The array of results gathered so far by
    //   the batch processing, for the current operation to append its own.
    // 'message' (write): A text message displayed in the progress page.
    // The following keys allow for multi-step operations :
    // 'sandbox' (read / write): An array that can be freely used to
    //   store persistent data between iterations. It is recommended to
    //   use this instead of the session, which is unsafe if the user
    //   continues browsing in a separate window while the batch is processing.
    // 'finished' (write): A float number between 0 and 1 informing
    //   the processing engine of the completion level for the operation.
    //   1 (or no value explicitly set) means the operation is finished
    //   and the batch processing can continue to the next operation.
    $nodes = \Drupal::entityTypeManager()->getStorage('node')
        ->loadByProperties([
        'uid' => $uid,
        'type' => $type,
    ]);
    $node = reset($nodes);
    $context['results'][] = $node->id() . ' : ' . Html::escape($node->label());
    $context['message'] = Html::escape($node->label());
}
// A more advanced example is a multi-step operation that loads all rows,
// five by five.
function my_function_2(&$context) {
    if (empty($context['sandbox'])) {
        $context['sandbox']['progress'] = 0;
        $context['sandbox']['current_id'] = 0;
        $context['sandbox']['max'] = \Drupal::database()->query('SELECT COUNT(DISTINCT [id]) FROM {example}')
            ->fetchField();
    }
    $limit = 5;
    $result = \Drupal::database()->select('example')
        ->fields('example', [
        'id',
    ])
        ->condition('id', $context['sandbox']['current_id'], '>')
        ->orderBy('id')
        ->range(0, $limit)
        ->execute();
    foreach ($result as $row) {
        $context['results'][] = $row->id . ' : ' . Html::escape($row->title);
        $context['sandbox']['progress']++;
        $context['sandbox']['current_id'] = $row->id;
        $context['message'] = Html::escape($row->title);
    }
    if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
        $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
    }
}

Sample callback_batch_finished():


function my_finished_callback($success, $results, $operations, $elapsed) {
  // See callback_batch_finished() for more information about these
  // parameters.
  // The 'success' parameter means no fatal PHP errors were detected. All
  // other error management should be handled using 'results'.
  if ($success) {
    $message = \Drupal::translation()->formatPlural(count($results), 'One item processed.', '@count items processed.');
  }
  else {
    $message = t('Finished with an error.');
  }
  \Drupal::messenger()->addMessage($message);
  // Providing data for the redirected page is done through the session.
  foreach ($results as $result) {
    $items[] = t('Loaded node %title.', ['%title' => $result)];
  }
  $session = \Drupal::getRequest()->getSession();
  $session->set('my_batch_results', $items);
}

File

core/includes/form.inc, line 563

Functions

Title Sort descending File name Summary
batch_get core/includes/form.inc Retrieves the current batch.
batch_process core/includes/form.inc Processes the batch.
batch_set core/includes/form.inc Adds a new batch.
hook_batch_alter core/lib/Drupal/Core/Form/form.api.php Alter batch information before a batch is processed.
_batch_append_set core/includes/form.inc Appends a batch set to a running batch.
_batch_populate_queue core/includes/form.inc Populates a job queue with the operations of a batch set.
_batch_queue core/includes/form.inc Returns a queue object for a batch set.

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