Batch Process In Drupal

Batch processing is the execution of a series of jobs in a site without manual intervention each on a set or “batch” of inputs, rather than a single input. Batch operations in Drupal API is primarily designed to integrate nicely with the Form API workflow, but can also be used by non-Form API scripts.

1) Build a url using hook_menu to execute batch process.

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items = array();

  // Create a page with URL admin/batch
  $items['admin/batch'] = array(
    'title' => 'Demo Batch',
    'description' => 'Run batch operations.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MYMODULE_batch_form'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
   );

  return $items;
}

2) Callback function for batch process MYMODULE_batch_form.

/**
 * Callback function.
 * Create submit button in the form on admin/batch page
 */
function MYMODULE_batch_form(){
  $form = array();
  $form['submit'] = array('#type' => 'submit', '#value' => t('Start batch process'));
  return $form;
}

3) Submit function to set batch process. This just passes a function name to the batch API. The referenced function should build the array which tells batch API what to do. 

/**
 * Submit function for form.
 * Set the batch process to start on form submit.
 */
function MYMODULE_batch_form_submit($form, $form_state){
  batch_set(MYMODULE_build_batch());
}

4) Create the list of operations to call when the batch starts. Here we essentially build an array of future function calls, with arguments, and a finished function.

The important thing here is the $operations array. When the batch starts it will loop through $operations array.

/**
 * Generate batch process & its operations.
 */
function MYMODULE_build_batch() {
  $operations = array();

  // Here we can add multiple operation
   $operations[] = array('MYMODULE_process_data', array($arg1)); // operation with argument
   $operations[] = array('MYMODULE_process_data'); // operation without argument

  //Define your batch operation here
  $batch = array( 
    'title' => t('Batch operation processing'),
    'operations' => $operations,
    'finished' => 'MYMODULE_build_batch_finished',
    'init_message' => t('Initializing...'),
    'progress_message' => t('Operation @current out of @total.'),
    'error_message' => t('Found some error here.'),
    'file' => drupal_get_path('module', 'MYMODULE') . 'MYMODULE.module',
  );

  return $batch;
}

5) Create the operation code. This is the actual operation part – the thing that does the work. The arguments it receives will come from the $operations[] loop in step 4 above. Note the additional $context argument. This is in addition to the ones we provided in step 4 and lets us converse with the batch. This is useful for passing back status messages, etc.

 /**
 * This is the function that is called on each operation of batch process.
 */
function avert_replace_url_ru_batch_process($arg1 = '', &$context) {

  // Optional message displayed under the progressbar.
  $context['message'] = t('Now Processing....');

  $updated = FALSE;

  try {
    LOGIC FOR YOUR OPERATION...

    $updated = TRUE;
  }
  catch (\PDOException $e) {
    $error = $e->getMessage();
  }

  if ($updated) {
    drupal_set_message("Updated.");
  }
}


6) Let the user know we have finished and if there were any errors.

 /**
 * Batch finished 
 * Function runs after batch process finishes.
 */
function avert_replace_url_ru_build_batch_finished($success, $results, $operations) {
  if ($success) {
    // Here we could do something meaningful with the results.
    // We just display the number of data we processed.
    drupal_set_message(t('@count tables  processed.', array('@count' => count($results))));
  } else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $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))));
  }
}

Feel free to contact us in-case of any concern/queries regarding the shared Blog or Drupal Development Services

Happy to help always 🙂 

Floating Icon 1Floating Icon 2