Drupal 8  8.0.2
Batch operations

Functions

 batch_set ($batch_definition)
 
batch_get ()
 
 _batch_populate_queue (&$batch, $set_id)
 
 _batch_queue ($batch_set)
 
 hook_batch_alter (&$batch)
 

Detailed Description

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 = array(
'title' => t('Exporting'),
'operations' => array(
array('my_function_1', array($account->id(), 'story')),
array('my_function_2', array()),
),
'finished' => 'my_finished_callback',
'file' => 'path_to_file_containing_myfunctions',
);
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 ::checkPlain() or ::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 $_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 = entity_load_multiple_by_properties('node', array('uid' => $uid, 'type' => $type));
$node = reset($nodes);
$context['results'][] = $node->id() . ' : ' . SafeMarkup::checkPlain($node->label());
$context['message'] = SafeMarkup::checkPlain($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'] = db_query('SELECT COUNT(DISTINCT id) FROM {example}')->fetchField();
}
$limit = 5;
$result = db_select('example')
->fields('example', array('id'))
->condition('id', $context['sandbox']['current_id'], '>')
->orderBy('id')
->range(0, $limit)
->execute();
foreach ($result as $row) {
$context['results'][] = $row->id . ' : ' . SafeMarkup::checkPlain($row->title);
$context['sandbox']['progress']++;
$context['sandbox']['current_id'] = $row->id;
$context['message'] = SafeMarkup::checkPlain($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) {
// 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 post processed.', '@count posts processed.');
}
else {
$message = t('Finished with an error.');
}
drupal_set_message($message);
// Providing data for the redirected page is done through $_SESSION.
foreach ($results as $result) {
$items[] = t('Loaded node %title.', array('%title' => $result));
}
$_SESSION['my_batch_results'] = $items;
}

Function Documentation

_batch_populate_queue ( $batch,
  $set_id 
)

Populates a job queue with the operations of a batch set.

Depending on whether the batch is progressive or not, the Drupal or Drupal handler classes will be used.

Parameters
$batchThe batch array.
$set_idThe id of the set to process.
Returns
The name and class of the queue are added by reference to the batch set.

References _batch_queue().

Referenced by batch_set().

Here is the call graph for this function:

Here is the caller graph for this function:

_batch_queue (   $batch_set)

Returns a queue object for a batch set.

Parameters
$batch_setThe batch set.
Returns
The queue object.

References Drupal\database().

Referenced by _batch_populate_queue().

Here is the call graph for this function:

Here is the caller graph for this function:

& batch_get ( )

Retrieves the current batch.

Referenced by batch_set(), FormSubmitter\batchGet(), LocaleController\checkTranslation(), BatchNegotiator\determineActiveTheme(), WebTestBase\restoreBatch(), WebTestBase\setBatch(), and ProgrammaticTest\testSubmissionWorkflow().

Here is the caller graph for this function:

batch_set (   $batch_definition)

Adds a new batch.

Batch operations are added as new batch sets. Batch sets are used to spread processing (primarily, but not exclusively, forms processing) over several page requests. This helps to ensure that the processing is not interrupted due to PHP timeouts, while users are still able to receive feedback on the progress of the ongoing operations. Combining related operations into distinct batch sets provides clean code independence for each batch set, ensuring that two or more batches, submitted independently, can be processed without mutual interference. Each batch set may specify its own set of operations and results, produce its own UI messages, and trigger its own 'finished' callback. Batch sets are processed sequentially, with the progress bar starting afresh for each new set.

Parameters
$batch_definitionAn associative array defining the batch, with the following elements (all are optional except as noted):
  • operations: (required) Array of operations to be performed, where each item is an array consisting of the name of an implementation of callback_batch_operation() and an array of parameter. Example:
    array(
    array('callback_batch_operation_1', array($arg1)),
    array('callback_batch_operation_2', array($arg2_1, $arg2_2)),
    )
  • title: A safe, translated string to use as the title for the progress page. Defaults to t('Processing').
  • init_message: Message displayed while the processing is initialized. Defaults to t('Initializing.').
  • progress_message: Message displayed while processing the batch. Available placeholders are , , , , and . Defaults to t('Completed of .').
  • error_message: Message displayed if an error occurred while processing the batch. Defaults to t('An error has occurred.').
  • finished: Name of an implementation of callback_batch_finished(). This is executed after the batch has completed. This should be used to perform any result massaging that may be needed, and possibly save data in $_SESSION for display after final page redirection.
  • file: Path to the file containing the definitions of the 'operations' and 'finished' functions, for instance if they don't reside in the main .module file. The path should be relative to base_path(), and thus should be built using drupal_get_path().
  • css: Array of paths to CSS files to be used on the progress page.
  • url_options: options passed to url() when constructing redirect URLs for the batch.
  • progressive: A Boolean that indicates whether or not the batch needs to run progressively. TRUE indicates that the batch will run in more than one run. FALSE (default) indicates that the batch will finish in a single run.
  • queue: An override of the default queue (with name and class fields optional). An array containing two elements:
    • name: Unique identifier for the queue.
    • class: The name of a class that implements , including the full namespace but not starting with a backslash. It must have a constructor with two arguments: $name and a object. Typically, the class will either be or . Defaults to Batch if progressive is TRUE, or to BatchMemory if progressive is FALSE.

References _batch_populate_queue(), batch_get(), and t().

Referenced by BatchTestChainedForm\batchTestChainedFormSubmit1(), BatchTestChainedForm\batchTestChainedFormSubmit2(), BatchTestChainedForm\batchTestChainedFormSubmit4(), BatchTestSimpleForm\submitForm(), BatchTestMultiStepForm\submitForm(), ImportForm\submitForm(), TranslationStatusForm\submitForm(), UpdateManagerUpdate\submitForm(), ConfigSync\submitForm(), BatchTestController\testFinishRedirect(), BatchTestController\testLargePercentage(), BatchTestController\testNestedDrupalFormSubmit(), BatchTestController\testNoForm(), BatchTestController\testThemeBatch(), BatchTestController\testTitleBatch(), DbUpdateController\triggerBatch(), and UpdateController\updateStatusManually().

Here is the call graph for this function:

Here is the caller graph for this function:

hook_batch_alter ( $batch)

Alter batch information before a batch is processed.

Called by batch_process() to allow modules to alter a batch before it is processed.

Parameters
$batchThe associative array of batch information. See batch_set() for details on what this could contain.
See Also
batch_set()
batch_process()