Drupal 8: How to redirect to batch form after submit to custom url (batch api)

I’ve been fighting with this for a long time but then I found simple solution.

I needed to redirect to new batch processing page right after clicking submit button so here is a solution

public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirectUrl(Url::fromUri())
    $identity = isset($form_state->getTriggeringElement()['#identity']) ? $form_state->getTriggeringElement()['#identity'] : 'unknown';
    switch ($identity) {
      case static::BTN_UPDATE;
        $batch = [
          'title' => t('Updating'),
          'operations' => [
            array('sfo_common_batch_callbacks__taxonomy_update_cache_process', [[]]),
          ],
          'finished' => 'sfo_common_batch_callbacks__taxonomy_update_cache_finished',
          'file' => drupal_get_path('module', 'sfo_common') . '/include/batch/sfo_common.taxonomy_cache.inc',
        ];

        batch_set($batch);
        $request =  batch_process(static::URL_REDIRECT);
        return $request->send();
        break;
      default:
        drupal_set_message(t('Incorrect operation'));
        break;
    }
  }

This is the usecase I found. But this is only works great for batch. If you need to redirect after form submit it is also possible to use

public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_state->setRedirect(taxonomy.vocabulary.collection); // Here need to pass route name from *.routes.yml file

  //But if you need to redirect to custom url
  $form_state->setRedirectUrl(Url::fromUri('http://google.com')); // Need to pass Drupal\Core\Url object here
}

Other ways to redirect https://www.drupal.org/node/2023537

Loading

This entry was posted in Nets, PHP, WEB, The Internet, Computers, BY, Programming and tagged , , , . Bookmark the permalink. | Short link:  http://p1rat.ru/lezzz/5KbGG

Leave a Reply