Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

How to redirect a user after login in Drupal the proper way

Parent Feed: 

There are several stable contrib modules available that offer redirecting users - often as one of many functionalities. In some cases however, you might want to write your own module in order to precisely control what it does. Or perhaps you would like to combine this code with other specific requirements into a custom module. 

Whatever your particular reason, here’s how redirect users the proper way in Drupal 8:

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

 * Implements hook_form_FORM_ID_alter().
function MYCUSTOMMODULE_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#submit'][] = 'MYCUSTOMMODULE_user_login_form_submit';

 * Custom submit handler for the login form.
function MYCUSTOMMODULE_user_login_form_submit($form, FormStateInterface $form_state) {
  $url = Url::fromRoute('/your/destination/path');

For Drupal 8 in particular, it is important to note that we no longer use hook_user_login(), because it would stop other implementations of that hook to be invoked. Instead, we’re adding a custom submit handler to the user login form.

Of course this is just a starting point. You could add certain conditions or redirect users to different paths depending on their user role. 


Hope this helps! Please don't be afraid to reach out if you need any help with your Drupal project. Our experts are always happy to help!

Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web