You are here

function roleassign_form_alter in RoleAssign 5

Same name and namespace in other branches
  1. 8 roleassign.module \roleassign_form_alter()
  2. 6 roleassign.module \roleassign_form_alter()
  3. 7.2 roleassign.module \roleassign_form_alter()
  4. 7 roleassign.module \roleassign_form_alter()

Implementation of hook_form_alter().

Adds checkboxes for assignable roles to the user edit form.

File

./roleassign.module, line 134

Code

function roleassign_form_alter($form_id, &$form) {

  // Do nothing if the user already has 'administer access control'
  // permission.
  if (user_access('administer access control')) {
    return;
  }

  // Do nothing if the user hasn't both 'administer users' and
  // 'assign roles' permissions.
  if (!user_access('administer users') || !user_access('assign roles')) {
    return;
  }

  // Do nothing if right form isn't shown.
  if ($form_id != 'user_register' && ($form_id != 'user_edit' || !isset($form['account']))) {
    return;
  }

  // Get all roles that are available.
  $roles = user_roles(true);

  // Get roles that are available for assignment.
  $assignable_roles = _roleassign_assignable_roles($roles);

  // Get roles already assigned to the user.
  // The use of the superfluous $user variable is required by PHP4.
  $user = user_load(array(
    'uid' => arg(1),
  ));
  $assigned_roles = $user->roles;

  // A user might already have a role that isn't avaiable for
  // assignment through this module. A such role is called "sticky".
  // Get sticky roles.
  $sticky_roles = array_diff($assigned_roles, $assignable_roles);
  $sticky_roles = array_intersect_key($roles, $sticky_roles);

  // Store sticky roles for later use in roleassign_user().
  _roleassign_sticky_roles($sticky_roles);

  // Make a string of all sticky roles.
  $sticky_roles[DRUPAL_AUTHENTICATED_RID] = $roles[DRUPAL_AUTHENTICATED_RID];
  foreach ($sticky_roles as $role) {
    $sticky_roles_str .= $role . ', ';
  }
  $sticky_roles_str = substr($sticky_roles_str, 0, strlen($sticky_roles_str) - 2);

  // Build the assign roles checkboxes.
  $roles_field = array(
    '#type' => 'checkboxes',
    '#title' => t('Assignable roles'),
    '#options' => $assignable_roles,
    '#default_value' => array_keys($assigned_roles),
    '#description' => t('The user receives the combined permissions of all roles selected here and following roles: %roles.', array(
      '%roles' => $sticky_roles_str,
    )),
  );

  // The user form is sometimes within an 'account' fieldset.
  if (isset($form['account'])) {
    $user_form =& $form['account'];
  }
  else {
    $user_form =& $form;
  }

  // Add the assign roles checkboxes to the user form, and make sure
  // that the notify user checkbox comes last.
  $notify_field = $user_form['notify'];
  unset($user_form['notify']);
  $user_form['roleassign_roles'] = $roles_field;
  $user_form['notify'] = $notify_field;
}