Dynamic redirect after a Batch API job

By nnevill, 14 July, 2023

It's not obvious that Batch API supports dynamic redirect after finishing the job. So you could e.g. create a node during batch and redirect the user to that node edit form on batch finish.


To do you have to pass the node ID parameter to $context variable inside batch operation:

/**
 * Batch operation.
 */
function batch_example_run($options1, $options2, &$context) {
  // Code to get $node_id.
  $node_id = 42;
  // Passing $node_id to batch API 'finished' callback.
  $context['results']['nid'] = $node_id;
}

Then you could use that node ID in batch `finished` callback to do the redirect:

  /**
   * Batch finish callback.
   *
   * @param bool $success
   *   Success flag.
   * @param array $results
   *   Array with results.
   * @param array $operations
   *   Array with operations.
   */
  function batchFinished($success, $results, $operations) {
    \Drupal::messenger()->addStatus('Finish!!!');
    // Redirect to node edit page.
    return new RedirectResponse(Url::fromRoute(
      'entity.node.edit_form',
      ['node' => $results['nid']]
    )->toString());
  }

The tricky thing here is that it was not mentioned in the documentation so I got that only after debugging. There is also an active thread on d.org with a request to update the documentation.

Short Description
Dynamic redirect after finishing batch API job.