Redirect a user after login. Redirection on Drupal 8. | Drupal 8

Redirect a user after login. Redirection on Drupal 8.

Submitted by editor on Tue, 05/23/2017 - 10:15
Question

How to redirect a user once logged on (on Drupal 8) ?

To make a redirection after user login, we can use the hook hook_user_login().
Note : You cannot use $form_state->setRedirectUrl() directly in the form alter, since it will be overwritten by UserForm::submitForm().

Example : We want to redirect a user to the page "mymodule.dashboard".
/**
 * Implements hook_user_login().
 */
function mymodule_user_login(\Drupal\user\UserInterface $account) {
  // Default login destination to the dashboard.
  $current_request = \Drupal::service('request_stack')->getCurrentRequest();
  if (!$current_request->query->get('destination')) {
    $current_request->query->set(
      'destination',
      \Drupal\Core\Url::fromRoute('mymodule.dashboard')->toString()
    );
  }
}

Tips : Page redirection. Redirect on a basic controller :

$url = \Drupal\Core\Url::fromRoute('user.login')->toString();
$current_request = \Drupal::service('request_stack')->getCurrentRequest();
$current_request->query->set('destination', $url);
return new \Symfony\Component\HttpFoundation\RedirectResponse($url);

CAUTION : The following example is nor workin, Do not use it.

$url = \Drupal\Core\Url::fromRoute('mymodule.DESTINATION_PAGE');
return new \Symfony\Component\HttpFoundation\RedirectResponse($url);

Add new comment