logo

Redirect Method in DRUPAL8

21
April

Redirect Method in DRUPAL8
By: Anonymous | Published On: Tue, 04/21/2020 - 23:44

To redirect on node add form or node creation form

$form_state->setRedirectUrl(Url::fromUri('internal:' . '/node/add/business'));

If you want to pass argument with URL

Example:

        $params['query'] = [
            'name' => $name,
            'id' => $id,
        ];
$form_state->setRedirectUrl(Url::fromUri('internal:' . '/node/add/business', $params));

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

Need Help ?