How do you set a user's group on a registration form? 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()-&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));
        }   
    });
}


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

&lt;input type="hidden" name="myHiddenInput" value="1"&gt;


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-&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]);
        }
    }
);


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