0

I don't want to show the default roles to end user and want to ignore anonymous user and authenticated user. How can I remove these two roles from roles array. Shall I hard code the role names and rid say as in example below?

I have used this code.

$ignore = array(1 => 'anonymous user', 2 => 'authenticated user');
$roles = user_roles();
$roles =  array_diff($roles, $ignore);

Thanks for your help.

  • Are you asking "Here's this code that works - will it always work?". – Chapabu Jun 13 '12 at 9:43
2

If you call user_roles(TRUE), the function will not return the anonymous user role.

Drupal always sets the role ID for anonymous user role, and the authenticated user role to the value of the constants DRUPAL_ANONYMOUS_RID, and DRUPAL_AUTHENTICATED_RID.

The following code is executed by user_install() in Drupal 7, and similar code is executed by system_install() in Drupal 6.

// Built-in roles.
  $rid_anonymous = db_insert('role')
    ->fields(array('name' => 'anonymous user', 'weight' => 0))
    ->execute();
  $rid_authenticated = db_insert('role')
    ->fields(array('name' => 'authenticated user', 'weight' => 1))
    ->execute();

  // Sanity check to ensure the anonymous and authenticated role IDs are the
  // same as the drupal defined constants. In certain situations, this will
  // not be true.
  if ($rid_anonymous != DRUPAL_ANONYMOUS_RID) {
    db_update('role')
      ->fields(array('rid' => DRUPAL_ANONYMOUS_RID))
      ->condition('rid', $rid_anonymous)
      ->execute();
  }
  if ($rid_authenticated != DRUPAL_AUTHENTICATED_RID) {
    db_update('role')
      ->fields(array('rid' => DRUPAL_AUTHENTICATED_RID))
      ->condition('rid', $rid_authenticated)
      ->execute();
  }

The following code works also in Drupal 5; the $roles array will not contain information about the anonymous user, and the authenticated user roles.

$roles = user_roles(TRUE);
unset($roles[DRUPAL_AUTHENTICATED_RID]);

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.