Skip to main content

Redirect the user login form to a different url in Drupal

The other day I was tasked with redirecting the Drupal login form to the user account page. On any other form this would work by adding the #redirect tag to the form in a form alter function like this:

  1. // Incorrect method, this doesn't work for the user login forms.
  2. function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  3.   switch($form_id) {
  4.     case 'user_login_block':
  5.     case 'user_login':
  6.       $form['#redirect'] = 'user';
  7.     break;
  8.   }
  9. }

However, the user login form uses the 'destination' URL parameter which overrides the #redirect in the form. In order to force the user login form and the user login block to redirect I needed to use the destination URL parameter like this:

  1.  
  2. function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  3.   switch($form_id) {
  4.     case 'user_login_block':
  5.     case 'user_login':
  6.       // Explode the form action and get the query string.
  7.       $url = explode('?', $form['#action']);
  8.       // Replace the query string with the destination I want, in this case the 'user' page.
  9.       $form['#action'] = $url[0] . '?destination=user';
  10.     break;
  11.   }
  12. }


Comments