I have a user_reference field in a content type. I want to remove all the users from it except from current user and administrators. Only administrator should see the complete users list.

I started by checking id=f current user is ad administrator.

function usersfilter_form_alter(&$form, &$form_state, $form_id) {
     global $user;
     if (in_array('administrator', array_values($user)){
        return; //administrator

Now I prepare the array that will be the new users list (can I just remove oart of the users instead?) and get the users list:

    $newUsers = array();
    $existingUsers = $form['field_users']['und']['#options'];

Finally I go over all the users. If this is the current user name, I'll add it. How can I check if this user is an administrator?

foreach ($existingUsers as &$existingUser) {
  if ($existingUser = $user->name) {
    $newUsers[] = $existingUser;

  // If administrator, add to the list.
  • As side note, there is a typo in your last snippet: You are using $existingUser = $user->name in the control statement when you should use $existingUser == $user->name.
    – apaderno
    May 23, 2012 at 9:27

2 Answers 2


In Drupal you should use the user_access() function with a specific permission to find out if the user has a certain level of access, not check their roles directly. The result is the same but it's just considered better practice to use the in-built permissions system.

You can use the user_load_by_name() function to load the user if you don't have the account id/user object already, e.g.:

$account = user_load_by_name($user_name);
if (user_access('access administration pages', $account)) {
  // Do something
  • thank you. that works. Just for documentation, here is the complete code pastebin.com/JH8x9RHz
    – Tibo
    May 23, 2012 at 9:07
  • @Tibo The reason user_access() should be used is that a permission could be added to more than one role. using user_access(), the code doesn't change (the permission is still the same, e.g. "administer nodes"); using in_array('administrator', $roles), the code could need to be changed, as you could need to check if the user don't have other roles too.
    – apaderno
    May 23, 2012 at 9:31

You can check what roles the user have with code similar to the following one:

global $user;

if (in_array('administrator', $user->roles)) {
  // The user is an administrator.
  • the variable $existingUser is just the user name. not the complete user object, right? so it has no property named "roles".
    – Tibo
    May 23, 2012 at 8:56
  • you get the current user always by using global $user; that object will get you the roles property. edited my answer to reflect that.
    – cmos
    May 23, 2012 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.