Skip to content

Instantly share code, notes, and snippets.

@pmichelazzo
Last active January 6, 2022 07:39
Show Gist options
  • Save pmichelazzo/68aafb67d2f7745db832ee141e6dbb7d to your computer and use it in GitHub Desktop.
Save pmichelazzo/68aafb67d2f7745db832ee141e6dbb7d to your computer and use it in GitHub Desktop.
The correct and best way to redirect an user after the login in Drupal 9

Redirect user after login in Drupal 9

The correct and best way to redirect an user after the login in Drupal 9

<?php

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) {
	// Do some stuff here, if you want.
	// If the destination path is not a regular Drupal path, e.g. a view, use
	// Url::fromUri('base:/your/destination/path'); instead of Url::fromRoute.
	$url = Url::fromRoute('/your/destination/path');
	$form_state->setRedirectUrl($url);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment