You are here

function administerusersbyrole_form_user_form_alter in Administer Users by Role 8.3

Same name and namespace in other branches
  1. 8.2 administerusersbyrole.module \administerusersbyrole_form_user_form_alter()

Implements hook_form_FORM_ID_alter().

Enable roles if required.

File

./administerusersbyrole.module, line 221
Administer Users by Role main module file.

Code

function administerusersbyrole_form_user_form_alter(&$form, &$form_state) {
  $user = $form_state
    ->getFormObject()
    ->getEntity();
  $account = Drupal::currentUser();

  // Allow empty email.
  // @todo Remove when https://www.drupal.org/node/2992848 is fixed.
  if (isset($form['account']['mail']) && !$user
    ->getEmail() && \Drupal::currentUser()
    ->hasPermission('allow empty user mail')) {
    $form['account']['mail']['#required'] = FALSE;
  }
  if (isset($form['account']['roles']) && administerusersbyrole_user_access($user, 'update', $account)
    ->isAllowed()) {
    $allowed = \Drupal::service('administerusersbyrole.access')
      ->listRoles('role-assign', $account);
    $options = array_intersect_key($form['account']['roles']['#options'], array_flip($allowed));
    $form['account']['roles']['#options'] = $options;

    // If there are no available options, hide the role form
    if (empty($options)) {
      $form['account']['roles']['#access'] = FALSE;
    }
  }
}