×

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

Read Article
Pause
Resume
Stop
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 custom.info 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) {
 batch_set(custom_batch_update_nodes());
}
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) {
   node_save($node);
   $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.

Comments

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