14

I create custom Form in Drupal 8 ,I remember we can redirect to custom path in Drupal 7 with set $form_state['redirect'] = 'mycustompath'; in custom submit handler, but how can redirect User after Form submission in Drupal 8?

I know I should use submitForm method:

public function submitForm(array &$form, FormStateInterface $form_state)
{
   //submissions jobs ...
   //redirect path
}
30

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 .. :)

  • 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? – Yusef Mohamadi May 26 '16 at 12:52
  • 1
    $form_state->setRedirect('<front>'); return; – parth.k May 26 '16 at 12:53
  • it shouldn't be '/start'. It is the alias mentioned in the routing file. – parth.k May 26 '16 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' – Yusef Mohamadi May 26 '16 at 12:58
  • It should be $form_state->setRedirect('tcdev.content'); – parth.k May 26 '16 at 12:59
7

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);
  • what is namespace of Url? Url' not found – Yusef Mohamadi May 26 '16 at 13:06
  • should be use Drupal\Core\Url; (without the preceding slash) – ummdorian Feb 24 '17 at 18:33
  • $form_state->setRedirectUrl($url); can also be used in submitForm(). – Shaun Dychko May 5 '17 at 9:11
  • Check the API: api.drupal.org/api/drupal/…. setRedirect() just converts the route to a URL first then calls setRedirectUrl(). – imclean Aug 7 '17 at 4:48
0

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.

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.