Custom Batch processing in Drupal 7 to update Nodes - Batch API

ByKarthik Kumar D Kon17th Aug 2015, 2022-12-01T08:00:00+05:30
Read Article
Custom Batch processing in Drupal 7 to update Nodes - Batch API

Drupal's batch API processing is very nice and provides few benifits, We can break long tasks into smaller batches, and by this we will be able to prevent maximum execution time errors.

This article will show how to Build a batch routine in a custom module, its more straight forward approach, you can follow up below code, which is been explained with required comments.

Create your custom module, which contains and custom.module files

The below code put in your custom.module file

function custom_menu() {
 $items['admin/custom_batch'] = array(
   'title' => 'Custom Batch',
   'description' => 'Custom Batch Process',
   'type' => MENU_NORMAL_ITEM,
   'access callback' => TRUE,
   'page callback' => 'drupal_get_form',
   'page arguments' => array('custom_batch_form'),
 return $items;
function custom_batch_form($form, $form_state) {
 $form["text"]['#markup'] = "Custom batch process to update nodes.... ";
 $form['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Run Batch'),
 return $form;
function custom_batch_form_submit($form, $form_state) {
function custom_batch_update_nodes() {
 drupal_set_message('Updating Nodes');
 $nodes = node_load_multiple(array(), array('type' => "story_song"));
 $node_count = count($nodes);
 foreach($nodes as $nid=>$node) {
   $operations[] = array('custom_batch_each_operation', array($node));
 $batch = array(
   'operations' => $operations,
   'finished' => 'custom_batch_update_nodes_finished',
 return $batch;
function custom_batch_each_operation($node, &$context) {
 $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
 $context['message'] = t('Processing node "@title"', array('@title' => $node->title));
 $updated = FALSE;
 if ($updated) {
   $path = drupal_lookup_path("alias", "node/" . $node->nid);
   drupal_set_message("<a href='/$path'>" . $node->title . "</a> updated.");
function custom_batch_update_nodes_finished($success, $results, $operations) {
 if ($success) {
   drupal_set_message(t('@count nodes processed.', array('@count' => count($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))));

Thank you.

We Need Your Consent
By clicking “Accept Cookies”, you agree to the storing of cookies on your device to enhance your site navigation experience.
I Accept Cookies