Jeremy French

My Site, still on Jekyll, now powered by github pages

2 March 2012

Drupal Batch API as simple as possible.

by Jeremy French

Drupal's batch API is a handy tool for processing multiple items giving you feedback on how a process is going and avoiding page timeouts or memory issues.

All that you need to be able to make use of the batch api is:

So say you wanted to amend a subset of nodes, you could write a query to retrieve the NIDs, create a function to do your amendment and use the batch api.

There is only one parameter you need to know for the batch api array and that is operations.

For the nodes you want to amend that would be something like:

<?php
$batch['operations'] = array(
  array('mymodule_ammend_node',1),
  array('mymodule_ammend_node',2),
  array('mymodule_ammend_node',3),
);

Of course you are more likely to create operations in a loop rather than hard coding

<?php
foreach ($nid_list as $nid) {
  $batch['operations'][] = array('mymodule_ammend_node',$nid);
}

Once you have your operations array created running a batch is very simple, this is all you need:

<?php
batch_set($batch); //See code above for batch array creation
batch_process();

There are a lot of other things that you can do with the batch API. But many times this simple case is all you need.

tags: drupal - batch api