Change record status: 
Project: 
Introduced in branch: 
8.6.x
Description: 

Before Drupal 8.6, batches were created through arrays and a functional programming approach.

$operations = array();
$operations[] = array('operation_callback', array(var1, var2, ...));
$batch = array(
  'operations' => $operations,
  'finished' => 'finished_callback',
  'title' => t('Processing Batch'),
  'init_message' => t('Batch is starting'),
  'progress_message' => t('Processed @current out of @total'),
  'error_message' => t('Batch has encountered an error'),
);
batch_set($batch);

In Drupal 8.6 and later, batches are created by using a Drupal\Core\Batch\BatchBuilder object and using methods to set the options.

use Drupal\Core\Batch\BatchBuilder;
$batch_builder = (new BatchBuilder())
  ->setTitle(t('Processing Batch'))
  ->setFinishCallback('finished_callback')
  ->setInitMessage(t('Batch is starting'))
  ->setProgressMessage(t('Processed @current out of @total.'))
  ->setErrorMessage(t('Batch has encountered an error'));
$batch_builder->addOperation('operation_callback', [var1, var2, ...]);
batch_set($batch_builder->toArray());
Impacts: 
Module developers

Comments

nanak’s picture

There's an error in the example, it should be
setFinishCallback('finish_callback')
instead of
setFinishedCallback('finished_callback')

manu manu’s picture

Corrected, thanks @nanak.

hygglo’s picture

Does it exist a working example for the new way to handle batches?

I just cannot get it to work.

danchadwick’s picture

"Batches are created" should be "batches may be created", as the array passed to batch_set() is the same regardless of whether is is built from a nested array or a functional-style set of methods. Also the characterization of functional style is reversed above; the new style is function, not the old style.

For someone setting about porting a D7 module to D8, this change records should be low on the list of priorities.

ultimike’s picture

When the setFile() method is used to specify the location of the batch functions, it must be called before setFinishCallback() or the finish callback will not be found:

$batch_builder = (new BatchBuilder())
  ->setTitle($this->t('Processing Batch'))
  ->setFile('/my_module.batch.inc')
  ->setFinishCallback('my_finish_callback_function')
  ->setInitMessage($this->t('Batch is starting'))
  ->setProgressMessage($this->t('Processed @current out of @total.'))
  ->setErrorMessage($this->t('Batch has encountered an error.'));