You are here

function access_grant_form_validate in Access Control Kit 7

Form validation handler for access_grant_form().

See also

access_grant_form()

access_grant_form_submit()

File

./access_grants.admin.inc, line 566
Access grants administrative UI for the access control kit module.

Code

function access_grant_form_validate($form, &$form_state) {
  $grant = $form_state['grant'];

  // Validate the properties of new grants.
  if (empty($grant->gid)) {

    // Validate the user reference.
    $account = user_load_by_name($form_state['values']['user']);
    if (empty($account)) {
      form_set_error('user', t('The username %name does not exist.', array(
        '%name' => $form_state['values']['user'],
      )));
    }
    else {
      $form_state['values']['uid'] = $account->uid;
    }

    // Validate the role reference.
    $role = user_role_load($form_state['values']['role']);
    $scheme = access_scheme_machine_name_load($grant->scheme);
    if (empty($role)) {
      form_set_error('role', t('A role with ID %rid does not exist.', array(
        '%rid' => $form_state['values']['role'],
      )));
    }
    elseif (empty($scheme->roles[$role->rid])) {
      form_set_error('role', t('The %role role cannot be used in @scheme.', array(
        '%role' => $role->name,
      )));
    }
    elseif ($account && empty($account->roles[$role->rid]) && !user_access('administer users')) {
      form_set_error('role', t('%user is not a member of the %role role.  You must have administrative access to user accounts in order to add a user to a new role.', array(
        '%user' => $account->name,
        '%role' => $role->name,
      )));
    }
    else {
      $form_state['values']['rid'] = $role->rid;
    }

    // If the above tests passed, validate that the user-role-scheme combination
    // is unique.  Duplicate grants are not permitted.
    if (!form_get_errors()) {
      $existing = access_grant_load_by_condition(array(
        'uid' => $account->uid,
        'rid' => $role->rid,
        'scheme' => $grant->scheme,
      ));
      if (!empty($existing)) {
        $existing = reset($existing);
        form_set_error('', t('%user has already been granted access as %role in @scheme. Duplicate access grants are not permitted. Please <a href="@url">edit the existing grant</a> instead.', array(
          '%user' => $account->name,
          '%role' => $role->name,
          '@scheme' => $scheme->name,
          '@url' => url('admin/access/grant/' . $existing->gid . '/edit'),
        )));
      }
    }
  }
  entity_form_field_validate('access_grant', $form, $form_state);
}