<p>If you're looking for a <strong>Craft 3</strong> solution, I just got this set up on a project and hope it helps someone else out.</p>

<p>First you'll need to add a custom field to your form.  If you want your user to choose which field, then go with a dropdown or radio button and adjust the plugin logic below. My scenario required me using a hidden field and auto-filling in the value based on a query parameter in the url.</p>

<pre><code>&lt;input type="hidden" name="myHiddenInput" value="1"&gt;
</code></pre>

<p>In your custom plugin's primary class, <code>use</code> this service at the top of your file:</p>

<pre><code>use craft\services\Users;
</code></pre>

<p>and then in the <code>init()</code> function add this event and adjust the code to your liking:</p>

<pre><code>Event::on(
    Users::class,
    Users::EVENT_AFTER_ASSIGN_USER_TO_DEFAULT_GROUP,
    function(UserAssignGroupEvent $event) {

        // get your hidden input value, 1 for true, 0 for false
        $isInDifferentGroup = Craft::$app-&gt;getRequest()-&gt;post('myHiddenInput');

        if ($isInDifferentGroup) {
            $differentGroup = Craft::$app-&gt;userGroups-&gt;getGroupByHandle('differentGroupHandle');

            $userId = $event-&gt;user-&gt;id;
            $customGroupId = $differentGroup-&gt;id;

            // add more group ids to array in 2nd param to add user to multiple groups
            Craft::$app-&gt;getUsers()-&gt;assignUserToGroups($userId, [$customGroupId]);
        }
    }
);
</code></pre>

<p>Shout-out to Oliver Stark from <strong><a href="https://www.fortrabbit.com" rel="noreferrer">fortrabbit</a></strong> for helping me with this.</p>

CC BY-SA 4.0
2018-10-03T16:31:20.067Z
2018-10-03T16:31:20.067Z
Ryan
<p><strong>This answer was originally written for Craft 2.</strong> For a Craft 3 solution, see <a href="https://craftcms.stackexchange.com/a/27926/45">Ryan's answer</a> above.</p>
<hr />
<p>I literally just worked through this problem last week. Ran into the same issue, so I reached out to P&amp;T.</p>
<p>Turns out there is a &quot;catch&quot;... For a new user, the <code>$_POST['groups']</code> value is passed as an empty array. And because of the order that it's processed, that empty array will actually overwrite what you've set manually.</p>
<p>After working through it with Brad, this is the solution that worked for me:</p>
<pre><code>public function init() {
    parent::init();
    craft()-&gt;on('users.saveUser', function(Event $event) {
        // If new user
        if ($event-&gt;params['isNewUser']) {
            // If &quot;groups&quot; is in POST
            if (isset($_POST['groups'])) {
                // If not an array, it's an empty string
                if (!is_array($_POST['groups'])) {
                    // Set it to an array with the user group ID
                    $_POST['groups'] = array(2);
                } else {
                    // Merge in the user group ID with any existing ones.
                    $_POST['groups'] = array_merge($_POST['groups'], array(2));
                }
            }
        }
    });
}
</code></pre>

CC BY-SA 3.0
2014-08-12T06:27:48.110Z
anyway to do it without setting the post var? wondering why my code is not working.
Luke Holder
CC BY-SA 3.0
2014-08-12T06:36:36.940Z
Not at the moment. Brad and I worked through it a few different ways, this was the only way that truly worked.
Lindsey D
CC BY-SA 3.0
2014-09-06T04:15:26.323Z
Where are you putting this code?
Matt Green
CC BY-SA 3.0
2014-09-06T04:55:32.673Z
Hey @Matt, I'm not sure of your specific situation... but last night I built a plugin to solve my problem: https://github.com/lindseydiloreto/craft-autoassignusergroup . After you've installed the plugin, go to **Settings > Auto-Assign User Group** to specify what group(s) a new user should be assigned to. Email me (support@doublesecretagency.com) if you have any questions.
Lindsey D
CC BY-SA 3.0
2014-09-06T05:10:15.570Z
ahhh. I see. Thanks, I simply just need to allow new users to select options which will assign them to the group they select, (needs to be secure so I'll get creative). I will use this as a base to start from thanks!
Matt Green
CC BY-SA 3.0
2014-09-06T05:12:42.970Z
Sounds great, figured your needs were different from mine... Feel free to backwards-engineer that plugin as needed! :)
Lindsey D
CC BY-SA 4.0
2019-07-11T16:22:15.787Z
I can't the example above to work on Craft 3.2, can I check the complete code for this... is the only service line needed at the top still `use craft\services\Users;`?
James Greig
CC BY-SA 4.0
2019-07-11T16:59:43.717Z
@JamesGreig This question is almost 5 years old, and the posted snippet is for Craft 2.x (or maybe even 1.x). I’d highly recommend starting a brand new question, and just link back to this thread for reference.
Lindsey D
CC BY-SA 4.0
2014-08-11T16:39:30.390Z
2020-09-09T16:50:26.370Z
2020-09-09T16:50:26.370Z
Lindsey D
<p>Just wanted to add some additional info for anyone who comes across this thread. I also needed to check if, and handle accordingly if a user belonged to a specific group upon registration from my plugin. </p>

<p>Here is what that looks like:</p>

<p><strong>MyPlugin.php</strong></p>

<pre><code>craft()-&gt;on('users.onSaveUser', function (Event $event) {
    if (craft()-&gt;request-&gt;isCpRequest()) {
        error_log((craft()-&gt;config-&gt;get('devMode')) ? 'User is getting created from CP.' : '');

        if (isset($_POST['groups'])) {
            if (empty($_POST['groups'])) {
                // User does not have a user group.
            } else {
                foreach ($_POST['groups'] as $group) {
                    if ($group == 1) {
                        $this-&gt;_registerAccount($event);
                    } else {
                        // Not who I'm looking for.
                    }
                }
            }
        }
    } else {
        error_log((craft()-&gt;config-&gt;get('devMode')) ? 'User is getting created from the front-end.' : '');

        $this-&gt;_registerAccount($event);
    }
});
</code></pre>

CC BY-SA 3.0
2016-12-05T01:59:35.363Z
2016-12-05T01:59:35.363Z
Damon
<p>If you disable the email confirmation on your site, you can also use this:
(But <a href="https://craftcms.stackexchange.com/users/4433/ryan">Ryan</a>'s answer still better though)</p>

<pre class="lang-php prettyprint-override"><code>Event::on(Users::class, Users::EVENT_AFTER_ACTIVATE_USER, function (UserEvent $e) {

    //Tapping into the post to get the user group's handle
    $selectedUserGroupHandle = Craft::$app-&gt;request-&gt;post('user-group');

    //Find the corresponding user group
    $userGroup = UserGroup::find()-&gt;where(['handle' =&gt; $selectedUserGroupHandle])-&gt;one();

    //We've found the user group
    if ($userGroup){

        $groupIds = [
            $userGroup-&gt;id
        ];

        $user = $e-&gt;user;

        //This is legacy code from the UsersController.php
        Craft::$app-&gt;getUsers()-&gt;assignUserToGroups($user-&gt;id, $groupIds);
    }

});
</code></pre>

<p>You will need a custom input field (or select or whatever) on your form to post the user group's handle. In my case, that was user-group.</p>

<pre class="lang-html prettyprint-override"><code>&lt;input type="hidden" name="user-group" value="yourUserGroupHandle"&gt;
</code></pre>

<p>p.s.: </p>

<pre class="lang-php prettyprint-override"><code>use craft\events\UserEvent;
use craft\records\UserGroup;
use craft\services\Users;
</code></pre>

CC BY-SA 4.0
2019-08-08T12:01:58.433Z
2019-08-08T12:01:58.433Z
HunWalk
<p>Surprised not to see the Groupie plugin referenced anywhere here, which does exactly this: <a href="https://github.com/kinoli/groupie" rel="nofollow noreferrer">https://github.com/kinoli/groupie</a></p>

<p>(I am not the developer of it, just a happy user!)</p>

CC BY-SA 4.0
2019-11-06T10:27:04.230Z
2019-11-06T10:27:04.230Z
iamkeir
<p>In a registration form with public signup possible, how do you set the user group for a particular form?</p>

<p>As a stop-gap I am attempting to use the following code:</p>

<pre><code>function init()
{
    craft()-&gt;on('users.saveUser', function(Event $event)
    {
        $user = $event-&gt;params['user'];

        if( $user-&gt;leader == true )
        {
            craft()-&gt;userGroups-&gt;assignUserToGroups($user-&gt;id, array(2));
        }   
    });
}
</code></pre>

<p>I created a field (lightswitch) called leader to enable me to check the value after saving the user and adding them to the group. The above code is not working though.</p>

<p>Using <code>var_dump($user-&gt;leader)</code> I can see the true and false being returned on user, and also the <code>$user-&gt;id</code> is returning the user's id, but the group (2) is not being assigned. Think I am missing something obvious. Thanks.</p>

CC BY-SA 3.0
2014-08-11T11:14:20.110Z
Also, I understand this could be a security concern since a user may be able to change the value but want to do it anyway.
Luke Holder
CC BY-SA 3.0
2015-12-31T03:27:43.633Z
So, this exact code works for me. Did something possibly change in the year since this question was asked?
Peter Tell
<craft3><registration><user-groups><frontend-form>
How do you set a user's group on a registration form?
# How do you set a user's group on a registration form?

(Asked by: username_0 on 2014-08-11)

In a registration form with public signup possible, how do you set the user group for a particular form?
As a stop-gap I am attempting to use the following code:
function init()
{
    craft()->on('users.saveUser', function(Event $event)
    {
        $user = $event->params['user'];

        if( $user->leader == true )
        {
            craft()->userGroups->assignUserToGroups($user->id, array(2));
        }   
    });
}

I created a field (lightswitch) called leader to enable me to check the value after saving the user and adding them to the group. The above code is not working though.
Using var_dump($user->leader) I can see the true and false being returned on user, and also the $user->id is returning the user's id, but the group (2) is not being assigned. Think I am missing something obvious. Thanks.

**Tags:** craft3, registration, user-groups, frontend-form

> **Comments:**
> **username_0**: Also, I understand this could be a security concern since a user may be able to change the value but want to do it anyway.  
> **username_1**: So, this exact code works for me. Did something possibly change in the year since this question was asked?  

---

## 5 answers

### Answer by username_2 on 2018-10-03. Score: 7

If you're looking for a Craft 3 solution, I just got this set up on a project and hope it helps someone else out.
First you'll need to add a custom field to your form.  If you want your user to choose which field, then go with a dropdown or radio button and adjust the plugin logic below. My scenario required me using a hidden field and auto-filling in the value based on a query parameter in the url.


In your custom plugin's primary class, use this service at the top of your file:
use craft\services\Users;

and then in the init() function add this event and adjust the code to your liking:
Event::on(
    Users::class,
    Users::EVENT_AFTER_ASSIGN_USER_TO_DEFAULT_GROUP,
    function(UserAssignGroupEvent $event) {

        // get your hidden input value, 1 for true, 0 for false
        $isInDifferentGroup = Craft::$app->getRequest()->post('myHiddenInput');

        if ($isInDifferentGroup) {
            $differentGroup = Craft::$app->userGroups->getGroupByHandle('differentGroupHandle');

            $userId = $event->user->id;
            $customGroupId = $differentGroup->id;

            // add more group ids to array in 2nd param to add user to multiple groups
            Craft::$app->getUsers()->assignUserToGroups($userId, [$customGroupId]);
        }
    }
);

Shout-out to Oliver Stark from fortrabbit for helping me with this.


---

### Answer by username_3 on 2014-08-11. Score: 4

This answer was originally written for Craft 2. For a Craft 3 solution, see username_2's answer above.

I literally just worked through this problem last week. Ran into the same issue, so I reached out to P&T.
Turns out there is a "catch"... For a new user, the $_POST['groups'] value is passed as an empty array. And because of the order that it's processed, that empty array will actually overwrite what you've set manually.
After working through it with Brad, this is the solution that worked for me:
public function init() {
    parent::init();
    craft()->on('users.saveUser', function(Event $event) {
        // If new user
        if ($event->params['isNewUser']) {
            // If "groups" is in POST
            if (isset($_POST['groups'])) {
                // If not an array, it's an empty string
                if (!is_array($_POST['groups'])) {
                    // Set it to an array with the user group ID
                    $_POST['groups'] = array(2);
                } else {
                    // Merge in the user group ID with any existing ones.
                    $_POST['groups'] = array_merge($_POST['groups'], array(2));
                }
            }
        }
    });
}

> **Comments:**
> **username_0**: anyway to do it without setting the post var? wondering why my code is not working.  
> **username_3**: Not at the moment. Brad and I worked through it a few different ways, this was the only way that truly worked.  
> **username_4**: Where are you putting this code?  
> **username_3**: Hey @Matt, I'm not sure of your specific situation... but last night I built a plugin to solve my problem: https://github.com/lindseydiloreto/craft-autoassignusergroup . After you've installed the plugin, go to **Settings > Auto-Assign User Group** to specify what group(s) a new user should be assigned to. Email me (support@doublesecretagency.com) if you have any questions.  
> **username_4**: ahhh. I see. Thanks, I simply just need to allow new users to select options which will assign them to the group they select, (needs to be secure so I'll get creative). I will use this as a base to start from thanks!  
> **username_3**: Sounds great, figured your needs were different from mine... Feel free to backwards-engineer that plugin as needed! :)  
> **username_5**: I can't the example above to work on Craft 3.2, can I check the complete code for this... is the only service line needed at the top still `use craft\services\Users;`?  
> **username_3**: @JamesGreig This question is almost 5 years old, and the posted snippet is for Craft 2.x (or maybe even 1.x). I’d highly recommend starting a brand new question, and just link back to this thread for reference.  

---

### Answer by username_6 on 2016-12-05. Score: 1

Just wanted to add some additional info for anyone who comes across this thread. I also needed to check if, and handle accordingly if a user belonged to a specific group upon registration from my plugin. 
Here is what that looks like:
MyPlugin.php
craft()->on('users.onSaveUser', function (Event $event) {
    if (craft()->request->isCpRequest()) {
        error_log((craft()->config->get('devMode')) ? 'User is getting created from CP.' : '');

        if (isset($_POST['groups'])) {
            if (empty($_POST['groups'])) {
                // User does not have a user group.
            } else {
                foreach ($_POST['groups'] as $group) {
                    if ($group == 1) {
                        $this->_registerAccount($event);
                    } else {
                        // Not who I'm looking for.
                    }
                }
            }
        }
    } else {
        error_log((craft()->config->get('devMode')) ? 'User is getting created from the front-end.' : '');

        $this->_registerAccount($event);
    }
});


---

### Answer by username_7 on 2019-08-08. Score: 1

If you disable the email confirmation on your site, you can also use this:
(But username_2's answer still better though)
Event::on(Users::class, Users::EVENT_AFTER_ACTIVATE_USER, function (UserEvent $e) {

    //Tapping into the post to get the user group's handle
    $selectedUserGroupHandle = Craft::$app->request->post('user-group');

    //Find the corresponding user group
    $userGroup = UserGroup::find()->where(['handle' => $selectedUserGroupHandle])->one();

    //We've found the user group
    if ($userGroup){

        $groupIds = [
            $userGroup->id
        ];

        $user = $e->user;

        //This is legacy code from the UsersController.php
        Craft::$app->getUsers()->assignUserToGroups($user->id, $groupIds);
    }

});

You will need a custom input field (or select or whatever) on your form to post the user group's handle. In my case, that was user-group.


p.s.: 
use craft\events\UserEvent;
use craft\records\UserGroup;
use craft\services\Users;


---

### Answer by username_8 on 2019-11-06. Score: 1

Surprised not to see the Groupie plugin referenced anywhere here, which does exactly this: <https://github.com/kinoli/groupie>

(I am not the developer of it, just a happy user!)


---

