Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Redirect a user after login. Redirection on Drupal 8.

By editor , 23 May, 2017
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);

Tags

  • Drupal 8
  • Code
  • Module
  • User
Form redirection on submit
Page Redirection on Drupal 8 / 9

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer