Thursday, January 12, 2012

Drupal - Custom Login Redirect to current page

To redirect an html login link to back to the current page, (You were on), we need to use $_SERVER['HTTP_REFERER'] with hook_form alter..
For example if you are using a link like...


any where in the site...


function custom_login_redirect_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login') {
   $form['#submit'][] = 'goback';// go back will be called on submit
  }
  $uri = request_uri();
  if (($uri == "/user/login") && (!isset($_SESSION['last_page']))) {
   $_SESSION['last_page'] = $_SERVER['HTTP_REFERER'];
  }
}

go back is the function that will be added to submit array to be called after login form is submitted..

Here we are keeping the URL of the last page in "$_SERVER['HTTP_REFERER']" and storing it to some session with name "last_page"

When submit is hit, it calls the function in '$form['#submit'][]' i-e "goback"


function goback(&$form) {
  drupal_goto($_SESSION['last_page']);
}

and thats it... lets put it altogether in .module file for module name "custom_login_redirect"


function custom_login_redirect_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login') {
    $form['#submit'][] = 'goback'; 
  }
$uri = request_uri();
  if (($uri == "/user/login") && (!isset($_SESSION['last_page']))) {
    $_SESSION['last_page'] = $_SERVER['HTTP_REFERER'];
  }
}
function goback(&$form) {
  drupal_goto($_SESSION['last_page']);
}

No comments:

Post a Comment