Redirect Method in DRUPAL8


Redirect Method in DRUPAL8
By: Anonymous | Published On: Wed, 04/22/2020 - 22:13

Method to redirect on node id url

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

Method to redirect on custom url

$url = Url::fromRoute('olsys.mycustom_dashboard');

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

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)


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

Need Help ?