You are here

function callback_batch_finished in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Form/form.api.php \callback_batch_finished()
  2. 7 modules/system/form.api.php \callback_batch_finished()
  3. 9 core/lib/Drupal/Core/Form/form.api.php \callback_batch_finished()

Complete a batch process.

Callback for batch_set().

This callback may be specified in a batch to perform clean-up operations, or to analyze the results of the batch operations.

Parameters

$success: A boolean indicating whether the batch has completed successfully.

$results: The value set in $context['results'] by callback_batch_operation().

$operations: If $success is FALSE, contains the operations that remained unprocessed.

string $elapsed: A string representing the elapsed time for the batch process, e.g., '1 min 30 secs'.

Related topics

File

core/lib/Drupal/Core/Form/form.api.php, line 116
Callbacks and hooks related to form system.

Code

function callback_batch_finished($success, $results, $operations, $elapsed) {
  if ($success) {

    // Here we do something meaningful with the results.
    $message = t("@count items were processed (@elapsed).", [
      '@count' => count($results),
      '@elapsed' => $elapsed,
    ]);
    $list = [
      '#theme' => 'item_list',
      '#items' => $results,
    ];
    $message .= \Drupal::service('renderer')
      ->render($list);
    \Drupal::messenger()
      ->addStatus($message);
  }
  else {

    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', [
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE),
    ]);
    \Drupal::messenger()
      ->addError($message);
  }
}