20

I created a custom form in Drupal 8. I remember we can redirect to custom path in Drupal 7 with $form_state['redirect'] = 'mycustompath'; in a submission handler.

How can I achieve the same in Drupal 8?

I know I should use submitForm().

public function submitForm (array &$form, FormStateInterface $form_state) {
   // Redirect users.
}

7 Answers 7

36

In your "submitForm" method write below code

 $form_state->setRedirect('machine_name');
 return;

where machine_name is the machine name mentioned in the routing file.

I hope this helps .. :)

7
  • not work. I try my custom route $form_state->setRedirect('/start');return; , let's suppose I want to redirect to home page. what is exact snippet?
    – Yuseferi
    May 26, 2016 at 12:52
  • 2
    $form_state->setRedirect('<front>'); return;
    – parth.k
    May 26, 2016 at 12:53
  • 1
    it shouldn't be '/start'. It is the alias mentioned in the routing file.
    – parth.k
    May 26, 2016 at 12:54
  • '<front>' worked what you about path alias ? this is my route tcdev.content: path: '/start' defaults: _controller: 'Drupal\tcdev\Controller\TrainingCenterController::content' _title: 'Start Training Center' requirements: _permission: 'access content'
    – Yuseferi
    May 26, 2016 at 12:58
  • 1
    It should be $form_state->setRedirect('tcdev.content');
    – parth.k
    May 26, 2016 at 12:59
9

If you want to set at buildform you need to use some routing path like.

use Drupal\Core\Url;

$url = Url::fromRoute('route.path');
$form_state->setRedirectUrl($url);
4
  • what is namespace of Url? Url' not found
    – Yuseferi
    May 26, 2016 at 13:06
  • should be use Drupal\Core\Url; (without the preceding slash)
    – ummdorian
    Feb 24, 2017 at 18:33
  • $form_state->setRedirectUrl($url); can also be used in submitForm(). May 5, 2017 at 9:11
  • 1
    Check the API: api.drupal.org/api/drupal/…. setRedirect() just converts the route to a URL first then calls setRedirectUrl().
    – imclean
    Aug 7, 2017 at 4:48
0

use Drupal\Core\Url;

// url to redirect
$path = '/my-path';
// query string
$path_param = [
 'abc' => '123',
 'xyz' => '456'
];
// use below if you have to redirect on your known url
$url = Url::fromUserInput($path, ['query' => $path_param]);
$form_state->setRedirectUrl($url);
0
use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Symfony\Component\HttpFoundation\RedirectResponse;

$redirect_to_thankyou = new RedirectResponse(Url::fromUserInput('/thankyou')->toString());
$redirect_to_thankyou->send();

Works in Drupal 9 - 9.0.7, if you just want to direct to a URL on your site (haven't tested it on external URLs), rather than ponce about with routing.

Put it at the end of your submitForm function in your class that extends FormBase.

1
  • RedirectResponse is for Controllers. Forms need redirect set on the form_state.
    – Christian
    Aug 5 at 7:50
0

This took me a while to figure out, so I thought I'd share.

I wanted to redirect the user to /admin after a custom admin form submission. I could not find the admin route in Google searches.

I grepped all the routing ymls in core:

find -name \*.routing.yml -exec grep -l "path: '/admin'" {} \;

...and found it in ./modules/system/system.routing.yml

system.admin:
  path: '/admin'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Administration'
  requirements:
    _permission: 'access administration pages'

So my form redirect is:

$form_state->setRedirect('system.admin');

Needed a cache clear before it worked.

0

Theres a lot of answers in here but none that correctly show how to redirect to a specific path.

Firstly, you want to set the redirect in your submit handler. You can add a new one to the form array in your form_alter;

$form['#submit'][] = 'my_form_submit_handler';

Sometimes you may need to add the handler to the submit button as well;

$form['actions']['submit']['#submit'][]  = 'my_form_submit_handler';

Its important to append the item to the submit array so that you don't remove any handlers that already exist.

Then, in your submit handler;

function my_form_submit_handler(&$form, FormStateInterface $form_state) {
  $form_state->setRedirect(URL::fromUserInput('/whatever/path/you/want'));
}

And thats it. Theres no return as more submit handlers may come after this one.

And dont use any Response returns like RedirectResponse. Their correct usage is in Controllers when returning a response to a request.

-1

If you want to redirect user edit form to the home page or other page follow below code.

First, add-hook - hook_form_alter`

function yourmodulename_form_alter(&$form, FormStateInterface $form_state, $form_id) 
{
    if ($form_id === 'your form id') {
    $form['actions']['submit']['#submit'][] = 'modulename_user_edit_form_submit';
  } 
}

after adding hook add below function

function modulename_user_edit_form_submit($form,  FormStateInterface &$form_state) {
  global $base_url; //set base path
  $response = new Symfony\Component\HttpFoundation\RedirectResponse($base_url ."/xyz"); //set url
  $response->send();
  return;
}

I hope this help.

3
  • Doesn't this bypass all the submit handlers that should fire after your handler?
    – joekers
    Dec 3, 2019 at 13:35
  • 1
    You should have only $form_state->setRedirect() in the form submit so that all the other submit handlers can be processed.
    – joekers
    Dec 3, 2019 at 14:09
  • RedirectResponse is not correct for form redirection. It is for Controller responses. As @joekers said, you just need to set the redirect.
    – Christian
    Aug 5 at 7:49

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.