Create a batch Drupal 7


/**
 * Implements hook_form().
 */
function _demo_batch_form($node, &$form_state) {
  $form = array();
  
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'submit',
  );
  
  return $form;
}

/**
 * hook_form() submit handler.
 */
function _demo_batch_form_submit($node, &$form_state) {
  $batch = _demo_batch();
 
  batch_set($batch);
}

/**
 * Demo batch.
 * 
 * Alter the node title from node ID {$nid} {$count} times.
 */
function _demo_batch() {

  $nid = 150;
  $count = 500;
  $operations = array();
  
  for ($i = 0; $i  $operations,
    'finished' => '_demo_batch_finished',
  );
  return $batch;
 
}

/**
 * Batch executer.
 * 
 * @param int $nid
 */
function _demo_batch_exe($nid) {

  $node = node_load($nid);
  
  watchdog('Demo batch', 'Node @nid loaded', array('@nid'=> $nid));
  
  $node->title = 'Node title ' . rand(0, 15000);
  
  watchdog('Demo batch', 'Node @nid title changed to @title', array('@nid' => $nid, '@title' => $node->title));

  node_save($node);
  
  watchdog('Demo batch', 'Node @nid saved', array('@nid' => $nid));
  
}

/**
 * Batch finished callback.
 */
function _demo_batch_finished($success, $results, $operations) {
  if ($success) {
    watchdog('Demo batch', 'Batch finished, @results processed.', array('@results' => count($results)));
    drupal_set_message('Batch executed');
  }
  else {
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    watchdog('Demo batch', 'An error occured in the batch, hope you are ready to debug');
    drupal_set_message('An error occured', 'error');
  }
}

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.