Drupal 8 - Redirect to different pages from a form

By xngo on March 16, 2019

Overview

drupal_goto() has been removed in Drupal 8. In order to redirect to different pages, you have to use RedirectResponse class. See code below.

Creating routing for your test page

Add the routing information of your test page like the following:

tradesteps.form_redirection:
  path: '/form_redirection'
  defaults:
    _form: 'Drupal\tradesteps\Form\FormRedirection'
    _title: 'Form Redirection'
  requirements:
    _permission: 'access content'

Code in the form to redirect to different pages

<?php
namespace Drupal\tradesteps\Form;
 
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
 
use Symfony\Component\HttpFoundation\RedirectResponse;
 
class FormRedirection extends FormBase {
 
    public function buildForm(array $form, FormStateInterface $form_state) {
 
        $form['actions']['goto_front_page'] = [
            '#type' => 'submit',
            '#value' => $this->t('Goto front page'),
            '#submit' => array([$this, 'onGotoFrontPage']),
        ];
 
        $form['actions']['gotoFirstNode'] = [
          '#type' => 'submit',
          '#value' => $this->t('Goto first node'),
          '#submit' => array([$this, 'onGotoFirstNode']),
        ];            
 
        $form['actions']['gotoUserPage'] = [
          '#type' => 'submit',
          '#value' => $this->t('Goto user page'),
          '#submit' => array([$this, 'onGotoUserPage']),
        ];            
 
        return $form;
    }
    public function onGotoFrontPage(array &$form, FormStateInterface $form_state) {
        $url =  \Drupal\Core\Url::fromRoute('<front>');
        $response = new RedirectResponse($url->toString());
        $response->send();
    }
 
    public function onGotoFirstNode(array &$form, FormStateInterface $form_state) {
        $nid=1;
        $url =  \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid]);
        $response = new RedirectResponse($url->toString());
        $response->send();
    }
 
    public function onGotoUserPage(array &$form, FormStateInterface $form_state) {
        $url =  \Drupal\Core\Url::fromRoute('user.page');
        $response = new RedirectResponse($url->toString());
        $response->send();
    }
 
 
    public function submitForm(array &$form, FormStateInterface $form_state) {
    }
    public function getFormId() {
        return 'tradesteps_form_redirection';
    }
}

Test redirection form page

  1. Clear your cache.
  2. Open http://your-domain.com/form_redirection
  3. Click on the desired button.

Screenshot of redirection form

Github

  • https://github.com/xuanngo2001/drupal-form-redirection.git

Notes

  • You don't need send() if you are in Controller page.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.