You are here

function role_delegation_form_alter in Role Delegation 5

Same name and namespace in other branches
  1. 7 role_delegation.module \role_delegation_form_alter()

Implementation of hook_form_alter().

File

./role_delegation.module, line 164
This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the 'administer access control' permission.

Code

function role_delegation_form_alter($form_id, &$form) {

  // Only alter user form when user can't assign permissions without Role Delegation.
  if ($form_id != 'user_register' && $form_id != 'user_edit') {
    return;
  }
  if (user_access('administer access control')) {
    return;
  }

  // Split up roles based on whether they can be delegated or not.
  $current_roles = is_numeric(arg(1)) && ($user = user_load(array(
    'uid' => arg(1),
  ))) ? $user->roles : array();
  $rids_default = array();
  $rids_preserve = array(
    DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID,
  );
  $roles_preserve = array(
    'authenticated user',
  );
  $roles_options = array();
  $roles = _role_delegation_roles();
  foreach ($roles as $rid => $role) {
    if (user_access('assign all roles') || user_access(_role_delegation_make_perm($role))) {
      if (array_key_exists($rid, $current_roles)) {
        $rids_default[] = $rid;
      }
      $roles_options[$rid] = $role;
    }
    else {
      if (array_key_exists($rid, $current_roles)) {
        $rids_preserve[$rid] = $rid;
        $roles_preserve[] = $role;
      }
    }
  }
  if (empty($roles_options)) {

    // No role can be assigned.
    return;
  }

  // Generate the form items.
  $form['roles_preserve'] = array(
    '#type' => 'value',
    '#value' => $rids_preserve,
  );
  $assign_item = array(
    '#type' => 'checkboxes',
    '#title' => t('Roles'),
    '#description' => t('The user receives the combined permissions of the %roles role(s), and all roles selected here. ', array(
      '%roles' => implode(', ', $roles_preserve),
    )),
    '#options' => $roles_options,
    '#default_value' => $rids_default,
  );
  if (isset($form['account'])) {
    $form['account']['roles_assign'] = $assign_item;
  }
  else {
    $form['roles_assign'] = $assign_item;
  }
}