4

I'm working on setting up a batch process in Drupal 8 that will gather a bunch of remote information for a collection of entities, cache it, and create a list of the results on its own page. The batch process is kicked off from a form using batch_set().

The batch job runs fine, but I'm not sure how to do the redirect at the end. Since Drupal 8 uses RedirectResponse objects or $this->redirect('user.page'); in a controller and the callback for a batch job doesn't have a return type, I'm not sure what to use to trigger the redirect.

I've tried using the url_options value of the batch job definition but that's not working.

$batch = [
  'title'    => $this->t('job running'),
  'init_message' => $this->t('starting job'),
  'operations'  => $ops,
  'finished' => '\Drupal\my_module\MyClass::finished',
  'url_options' => [
    'query' => [
      'destination' => '/job/results',
    ],
  ],
];
7

Apparently I needed to ask to see the answer: return a RedirectResponse from the finish callback:

public static function finished($success, $results, $operations) {
  if ($success) {
    // Here we do something meaningful with the results.
    $message = t("@count tasks were done.", array(
      '@count' => count($results),
    ));
    drupal_set_message($message);
  }

  return new RedirectResponse('/job/results');
}

As far as I can tell this is an undocumented behavior.

From the helpful comment below, you can also add batch_redirect on the batch array that's either a string or Url object:

$batch = [
  'title'    => $this->t('job running'),
  'init_message' => $this->t('starting job'),
  'operations'  => $ops,
  'finished' => '\Drupal\my_module\MyClass::finished',
  'batch_redirect' => '/job/results',
];
  • 4
    According to \batch_process(), you can also set 'batch_redirect' on the batch array to either a string or Url object or pass it to that function, which is documented on the docblock of batch_set(). The thing is that you don't need to call that function yourself in a form API submit callback, which is the most common use case, so yes, not very obvious. batch API isn't exactly the best documented API in Drupal :) – Berdir Dec 6 '16 at 22:28
  • @Berdir thanks for the tip. I went looking for something like that and obviously failed to find it. – acrosman Dec 7 '16 at 19:53
2

This does not seem to work when creating the batch in a form submit handler, the redirect part in $batch is simply ignored.

Redirecting from the submit handler like this works for me:

$form_state->setRedirect('route.name');

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.