CMS, Uncategorized

Drupal8 batch operations

Batch operations are processes that are executed in batches on a single request. For example, we have multiple operations to perform but we want them to be executed in one go then we can use batch operations. It executes each operation asynchronously using AJAX call thereby reducing server load.

In this blog, we will explore about how to create and process batch operations in Drupal8.

To create a batch job in Drupal, the function batch_set can be used.

$records = [];// The records to process. This can contain query results etc.
$batch = [
 'title' => t('Batch operation under progress'),
 'operations' => [
   // Add more operation
 'finished' => '::onFinishBatchCallback',

Function batch_set expects one argument which is an associative array containing the following keys:

title: The page title to display while the batch process is in progress.
oerations: An Array of operations to be performed. Each array must contain two values. The first parameter should be a function name which will handle the batch operation and the second parameter is an array of arguments to the function.
finished: A function name which will be called when the batch job is finished.

Function to handle a batch operation:

 * Function to handle a batch process
public static function performBatchAction($records, &$context){
  $results = [];// Array to count how many records processed
  foreach($records as $key=>$value){
    //Process logic goes here
    $results[] = 'Process result';
  $context['message'] = 'Operation performed sucessfully';
  $context['results'] = $results;

The following function will be called once the batch operation is finished:

 * Callback function once the process is finished.
public static function onFinishBatchCallback($success, $results, $operations) {
  if ($success) {
    $message = \Drupal::translation()->formatPlural(
      'One record processed.', '@count records processed.'
  } else {
    $message = t('Finished with an error.');
    drupal_set_message($message, 'error');

Once a batch operation is started the batch UI is loaded and all the operations are carried out by ajax call.

About The Author

Leave a Reply