4

I'd like to control where a user gets re-directed after login based on the user group. That is, userGroupA logs in and is sent to /templateA/_entry, while userGroupB logs in and is sent to /templateB/_entry.

I understand that postLoginRedirect can be used dynamically. Are there any examples of this?

Thanks!

Nathan D Huening
  • 355
  • 2
  • 10

2 Answers2

7

To set the setting dynamically, you’ll need to create a new plugin, which just has an init() method with this:

public function init()
{
    // Is this a login request?
    if (
        craft()->request->getActionSegments() === array('users', 'login') &&
        ($loginName = craft()->request->getPost('loginName')) !== null &&
        ($user = craft()->users->getUserByUsernameOrEmail($loginName)) !== null
    )
    {
        if ($user->isInGroup('userGroupA'))
        {
            craft()->config->set('postLoginRedirect', 'path/a');
        }
        else if ($user->isInGroup('userGroupB'))
        {
            craft()->config->set('postLoginRedirect', 'path/b');
        }
    }
}

If none of the conditions match, then Craft will stick with whatever’s in your craft/config/general.php file.

Brandon Kelly
  • 34,307
  • 2
  • 71
  • 137
2

You could set the template they get redirected to after successfully logged in, then in there, redirect them based on the user group they belong to.

{% if currentUser.isInGroup('userGroupA') %}
    {% redirect 'path/a' %}
{% elseif currentUser.isInGroup('userGroupB') %}
    {% redirect 'path/b' %}
{% else %}
    {% redirect 'path/c' %}
{% endif %}
Brandon Kelly
  • 34,307
  • 2
  • 71
  • 137
Brad
  • 487
  • 3
  • 11
  • That's an interesting approach! I like the idea of adding the URL to a custom field of the member group, since it would be useful for other user-specific sections / data, as well. I'm hoping though that someone can describe an example of using postLoginRedirect dynamically! – Nathan D Huening Feb 27 '17 at 18:30
  • I can't think of a way for it to be dynamic unless there is some event that is called to change the value being passed to postLoginRedirect. And I don't if its possible to add some session logic into the general config file itself. – Brad Feb 27 '17 at 18:54
  • 1
    Brandon's answer is good, my answer would work as well if you don't want to build a plugin. – Brad Feb 27 '17 at 18:55
  • 2
    This is a great lo-fi solution. Just updated it to make it actually work, for anyone that wants to go this route instead. – Brandon Kelly Feb 27 '17 at 19:00
  • 1
    Agreed! Happy to throw together a plugin if necessary but nice to know there's a quick-and-dirty solution (which is all I need most of the time). Thanks Brad – Nathan D Huening Mar 01 '17 at 15:48