2

I have a page which uses the form api. When I go to that page via hook_menu I want to run a batch script.

I have looked at the batch example module and have come up with the following:

My page code

...

batch_set(my_batch());
die(); // removing this has no affect

...

Rest of the code

function my_batch() {
  $max = 10000;
  $increment = 1000;

  drupal_set_message(t('Creating batch'));

  $operations = array();

  for ($i = 0; $i < $max; $i = $i + $increment) {
    $operations[] = array(
      'batch_example_op_1',
      array(
        $i,
        $increment
      ),
    );
  }
  $batch = array(
    'operations' => $operations,
    'finished' => 'batch_example_finished',
  );
  return $batch;
}

/**
 * Batch operation for batch 1: load a node.
 *
 * This is the function that is called on each operation in batch 1.
 */
function batch_example_op_1($count, $increment) {
  drupal_set_message('Count is : ' . $count);
  $context['results'][] = time();
}

function batch_example_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('All done');
  }
  else {
    drupal_set_message('Error');
  }
}

Currently the $operations array is being created and is being passed to batch_set() then nothing else is happening.

  • My first thought was that die(); was the culprit because clearly, with it, it's pretty normal that nothing happens: die();` immediately exits from the entire script, i.e. the most external nesting level, index.php. But you comment that "removing this has no effect", so the problem might be elsewhere: could you show more of your page code? – cFreed Sep 6 '15 at 11:34
4

Based from the first sample code found in Drupal's Batch API page, it says,

If this function was called from a form submit handler, stop here, FAPI will handle calling batch_process(). If not called from a submit handler, add the following, noting the url the user should be sent to once the batch is finished.

And that we need to add the batch_process('node/1'); (still based from the sample code). So you just need to add this line of code with the Drupal path where you want the user to be redirected after the batch process after the batch_set() line.

The die() line also isn't needed anymore based on the sample code. I have also tested your code on my local D7 site with the batch_process() addition.

Unrelated Update

In your for loop declaration for ($i = 0; $i < $max; $i = $i + $increment), I noticed that the afterthought section doesn't increment the loop because the variables $i and $increment has no incremental operation.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.