I want to programmatically redirect a user after login. I use

<?php
function hook_form_alter(&$form, $form_state, $form_id) {
  switch (
$form_id) {
        
    case
'user_login':
     
$form['#redirect'] = 'desk';
     
      break;
   
    case
'user_login_block':
     
$form['#redirect'] = 'desk';
   
      break;
}
?>

That works fine if for the user_login but not for user_login_block, i.e. if the login occurs via a block.

Comments

WorldFallz’s picture

wouldn't the login destination module be easier?

_
Care about the future of the Drupal.org forums? Please join our conversation and show support for improving the forums infrastructure.

scoorch’s picture

Thanks, I knew the module but wanted to do it programmatically. login destinations seems to be rather hard coded in that point and I do not need all the administration overload.

jscoble’s picture

You can also try the front page module, but that would also necessitate some administration.

kyle_mathews’s picture

after much pain, I figured out how to redirect this block. Basically, you need to change #action not #redirect.

The user_login_block sets the action as follows:

<?php
function user_login_block() {
 
$form = array(
   
'#action' => url($_GET['q'], array('query' => drupal_get_destination())),
   
'#id' => 'user-login-form',
   
'#validate' => user_login_default_validators(),
   
'#submit' => array('user_login_submit'),
  );
?>

For whatever reason, doing form_alter and adding a redirect doesn't work when the destination is set. To fix it, in my hook_form_alter I did the following:

<?php
 
switch ($form_id) {

    case
'user_login_block':
      if(
registration_form_needs_info()) {
       
$form['#action'] = "node?destination=register";
      }
      break;
?>

Change register (obviously) to whatever url you want to redirect to. It seems that it's important to leave the node in the first part of the url as otherwise, the user won't be logged in.

Kyle Mathews

WildKitten’s picture

You can also use rules module. It is great for redirection, sending emails, and doing lot of things that need some sort of automatics.

kyle_mathews’s picture

Yeah -- in the light of the day I figured I do need to do that. The point of my code was to redirect the user on login if they were missing information or if they were logging in for the first time. Hook_form_alter is evaluated __before__ the person has logged in so it doesn't know whether to redirect the person or not.

So, as you suggested, I used the rules modules and wrote some custom code which is evaluated when a user logs in:

<?php
if (empty($account->mail)) {
 
$_REQUEST['destination'] = "register";
}
?>

BTW, just as with my last bit of code -- you can't just use drupal_goto() as the destination that the user module sets will override your drupal_goto.

Kyle Mathews