Assuming you're using the core 'users/save-user'
action (as per the official User Profile form example) you can add a form input named groups
to enable group assignments.
Again, assuming you're posting the form to the core 'users/save-user'
controller action, Craft will handle permission checking for you. But, it's probably a good idea to not expose any user group options that the current user doesn't actually have the permission to assign users to. A quick way to do that is using the currentUser.can()
method within a Twig |filter
, checking the assignUserGroup:groupUid
permission for each group:
{% set userGroups = craft.app.userGroups.allGroups()|filter(group => currentUser.can("assignUserGroup:#{group.uid}")) %}
Once you have your userGroups
array, you can build a dropdown:
<form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
...
<label for="group">User group</label>
<select id="group" name="groups[]">
{% for userGroup in userGroups %}
<option value="{{ userGroup.id }}"{% if user.isInGroup(userGroup) %} selected{% endif %}>{{ userGroup.name }}</option>
{% endfor %}
</select>
...
</form>
Or if you prefer, checkboxes (notice the hidden input name="groups"
above the actual checkbox inputs; that's there to make it possible to submit the form without any groups checked):
<input type="hidden" name="groups" value/>
<fieldset>
<legend>User groups</legend>
{% for userGroup in userGroups %}
<label>
<input type="checkbox" name="groups[]" value="{{ userGroup.id }}"{% if user.isInGroup(userGroup) %} checked{% endif %} />
<span>{{ userGroup.name }}</span>
</label>
{% endfor %}
</fieldset>
Or radio buttons:
<fieldset>
<legend>User group</legend>
{% for userGroup in userGroups %}
<label>
<input type="radio" name="groups[]" value="{{ userGroup.id }}"{% if user.isInGroup(userGroup) %} checked{% endif %} />
<span>{{ userGroup.name }}</span>
</label>
{% endfor %}
</fieldset>