How do I limit one role per user?

I want to see a select form field, instead of checkboxes for roles when I go to /user/#/edit.
So far I tried overwriting the $form['account']['roles'] in template.php, replace the checkboxes with a select dropdown, but failed.


You will be best using hook_form_alter().

You can edit the registration form & user edit form and change the type in a custom module.

function register_form_alter(&$form, &$form_state, $form_id) {
  if ( $form_id= 'user_register_form') {
    $form['user-register-form']['roles'] = array(
      '#type' => 'radios'
      // …
  • $form['user-register-form'] doesn't exist. – timofey.com Nov 2 '11 at 22:36
  • this is about as close as I can get: function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) { if ( $form_id == 'user_register_form') { $form['account']['roles']['#type'] = 'select'; } } but it gives me Warning: array_filter() [function.array-filter]: The first argument should be an array in user_user_presave() (line 1261 of /home/servername/public_html/drupal/modules/user/user.module). – timofey.com Nov 2 '11 at 22:51
  • Yea, sorry I was just on way to a meeting so didnt have time to check it over. Looks like you on the right track now though :) – WestieUK Nov 3 '11 at 6:51

I finally got it working! The following will change the registration and profile forms to output role selection as a select form field.

Include the following in the module:

//replace roles checkboxes in registration form with select field
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  if ( $form_id == 'user_register_form') {
    $form['account']['roles']['#type'] = 'select';
    $form['account']['roles']['#required'] = TRUE;

//replace roles checkboxes in profile form with select field
function MYMODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  if ( $form_id == 'user_profile_form') {
    $form['account']['roles']['#type'] = 'select';
    $form['account']['roles']['#required'] = TRUE;

//hack for registration & profile forms, attaches the authenticated role
function MODULE_user_presave(&$edit, $account, $category) {
  if (isset($edit['roles'])) {
    is_array($edit['roles']) ? '' : $edit['roles'] = array ( $edit['roles'] => $edit['roles'], 2 => '1' );
    $edit['roles'] = array_filter($edit['roles']);

There is a module Single User Role to assign single role to per user. This module is also compatible with role delegation module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.