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 enablesave group assignments from a frontend form.
Again, assuming you're posting the form to the core 'users/save-user'
controller action, Craft will handle permission checking for you before the user
is saved. But, you should probably avoid exposing any user groups as options, that the current user isn't actually permitted to assign users to. One 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>