logo

Drupal8 Redirection

admin
22 Apr 2020

Method to redirect on node id url

$url = Url::fromRoute('entity.node.canonical', ['node' => $nid]);
$form_state->setRedirectUrl($url);

Method to redirect on custom url

$url = Url::fromRoute('olsys.mycustom_dashboard');
$form_state->setRedirectUrl($url);

Redirect on user view page of loggedin user

use Drupal\Core\Controller\ControllerBase; // Use this on top
return $this->redirect('user.page');	// use this as your code 

$url = \Drupal\Core\Url::fromRoute('olsys.nod_thanks')->setRouteParameters(array('nid'=>$nid,'uid'=>$uid));
$form_state->setRedirectUrl($url);	

Redirect on node detail page

$form_state->setRedirect('entity.node.canonical', ['node' => 2]);

Redirect on term detail page

$form_state->setRedirect('entity.taxonomy_term.canonical', ['taxonomy_term' => $tid]);

Redirect on views page (manager_banner is views name and page_5 is page name)

$form_state->setRedirect('view.manager_banner.page_5');

Redirect on custom path with their parameter value

$routeParameters = ['nid' => $nid];
$routeName = 'olsys.superappointment_status';				
$url = \Drupal::url($routeName, $routeParameters);
return new RedirectResponse($url);

Redirect at exter url In this example after submission should redirect to an external payment gateway, ceate a complete url then it should passed as link This should be use at top

use Drupal\Core\Routing\TrustedRedirectResponse;
$response = new TrustedRedirectResponse(Url::fromUri($link)->toString());
$form_state->setResponse($response);