Drupal Batch API

You, DrupalDrupal APIBatch API
Back

Batch API! What it does? It creates and processes batch operations :). What makes it so important? It is 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. Okay?. That's enought, let's jump in to some coding.

How to implement it?:

function YOUR_MODULE_SOME_FUNCTION() {
  // let's define our batch
  $batch = array(
    'title' => t('Importing friends ...'),
    'operations' => array(),
    'init_message' => t('Initializing'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error occurred during processing'),
    'finished' => 'YOUR_MODULE_batch_finished', // finished callback
    'progressive' => FALSE
  );

  // Let's create the batch operations operations sets
  foreach ($nodes as $node) { // This could be anything
   $batch['operations'][] = array('YOUR_MODULE_batch_worker', array(node)); // this is a funcation callback for each item of the batch
  }

  // set the batch
  batch_set($batch);
 // process the batch, <front> will take you to the home page of the site once finished.
  batch_process('<front>');
}


/**
 * Worker callback
 */

function YOUR_MODULE_batch_worker($node, &$context) {

  $context['message'] = t('Importing node "@title"', array('@title' => $node->title));
  $context['results']['processed']++;
}

/**
 * Finished callback
 */
function flag_open_graph_action_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('You\'ve imported  %final nodes.', array('%final' => end($results))));
  }
  else {
    $error_operation = reset($operations);
    drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE))));
  }
}
© Heshan Wanigasooriya.RSS

🍪 This site does not track you.