By john cook on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.6.x
Issue links:
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
There's an error in the
There's an error in the example, it should be
setFinishCallback('finish_callback')instead of
setFinishedCallback('finished_callback')Corrected, thanks @nanak.
Corrected, thanks @nanak.
Working example
Does it exist a working example for the new way to handle batches?
I just cannot get it to work.
"Batches are created" should
"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.
The order of chaining matters when using setFile()
When the
setFile()method is used to specify the location of the batch functions, it must be called beforesetFinishCallback()or the finish callback will not be found: