This has me beating my head on the desk a bit. I’m coding up a Drupal 6 module, and wanted to redirect the user after logging in, depending on what role they belong to.
In this example, let’s say I have a role called “treasurer” - and anyone that’s logged in and not a treasurer is an administrator. In my module (called mymod here), I knew that hook_user would do the trick somehow. Note that in hook_user, the $op variable contains what operation is being performed, and “login” is an option we can use here. So, this will fire right after the login form is processed and the user is loaded. The $account variable contains the entire $user object being worked on (so we can use it instead of a “global $user” declaration). Here’s what I originally wanted to do but it does not work:
function mymod_user($op, &$edit, &$account, $category = NULL) {
switch ($op) {
case 'login':
if (in_array('treasurer', $account->roles)) {
drupal_goto('user/' . $account->uid);
} else {
drupal_goto('admin/users');
}
break;
default:
// nothing
break;
}
}
We can’t use drupal_goto here, surprisingly. But after a little Googling, here is the way to do it - this works:
function mymod_user($op, &$edit, &$account, $category = NULL) {
switch ($op) {
case 'login':
if (in_array('treasurer', $account->roles)) {
$_REQUEST['destination'] = 'user/' . $account->uid;
} else {
$_REQUEST['destination'] = 'admin/user/user';
}
break;
default:
// nothing
break;
}
}
In short, we just need to set $_REQUEST['destination'] to whatever we want. In the above example, if the user is a treasurer, we sent them to their user account page. Otherwise, we know that it’s an administrator (since that’s the only other role I set up), and we show the admin all the users. Tailor to your needs. Note that if your destination has a url alias setup, this will automatically fetch the alias too. Cheers.
Thanks, This is what I needed, I will give it a try.
How do I take 301 redirect to the home page?
Madmax - you don’t need a module to do something like that - you can likely use .htaccess for such purposes. Just Google “drupal 301″ for some tips.
Thanks for the tip. Tried using triggers and actions but it never worked. This worked however.
is it possible to add another else statement in there if you want to add another role to redirect? so you would for example have treasurer, secretary, and everything else.
@gaforester - You can put as many “elseif” statements in there as you want, or just use another switch statement.
http://php.net/manual/en/control-structures.elseif.php
awesome, thanx! i’m a drupal user but not an expert coder…but i’m getting there. thanx again!