callback_batch_operation($MULTIPLE_PARAMS, &$context)
Perform a single batch operation.
Callback for batch_set().
$MULTIPLE_PARAMS: Additional parameters specific to the batch. These are specified in the array passed to batch_set().
array|\ArrayAccess $context.: The batch context array, passed by reference. This contains the following properties:
if (empty($context['sandbox'])) { // Perform set-up steps here. }
The values in the sandbox are stored and updated in the database between http requests until the batch finishes processing. This avoids problems if the user navigates away from the page before the batch finishes.
It is discouraged to typehint this parameter as an array, to allow an object implement \ArrayAccess to be passed.
function callback_batch_operation($MULTIPLE_PARAMS, &$context) { $node_storage = \Drupal::entityTypeManager()->getStorage('node'); $database = \Drupal::database(); if (!isset($context['sandbox']['progress'])) { $context['sandbox']['progress'] = 0; $context['sandbox']['current_node'] = 0; $context['sandbox']['max'] = $database->query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField(); } // For this example, we decide that we can safely process // 5 nodes at a time without a timeout. $limit = 5; // With each pass through the callback, retrieve the next group of nids. $result = $database->queryRange("SELECT nid FROM {node} WHERE nid > :nid ORDER BY nid ASC", 0, $limit, [':nid' => $context['sandbox']['current_node']]); foreach ($result as $row) { // Here we actually perform our processing on the current node. $node_storage->resetCache(array($row['nid'])); $node = $node_storage->load($row['nid']); $node->value1 = $options1; $node->value2 = $options2; node_save($node); // Store some result for post-processing in the finished callback. $context['results'][] = $node->title; // Update our progress information. $context['sandbox']['progress']++; $context['sandbox']['current_node'] = $node->nid; $context['message'] = t('Now processing %node', array('%node' => $node->title)); } // Inform the batch engine that we are not finished, // and provide an estimation of the completion level we reached. if ($context['sandbox']['progress'] != $context['sandbox']['max']) { $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max']; } }
© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Form!form.api.php/function/callback_batch_operation/8.1.x