Question

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
}
Était-ce utile?

La solution

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

Autres conseils

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);

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.


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

Licencié sous: CC-BY-SA avec attribution
Non affilié à drupal.stackexchange
scroll top