Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't user_load return any values for a user's roles?
    text
    copied!<p>So I have this code in a template:</p> <pre><code>$thisuser = user_load(array('uid' =&gt; '11812')); </code></pre> <p>which, as far as I understand it, should return a user object for the user with the uid of 11812. And that object should contain an array of roles for that user in this variable:</p> <pre><code>$thisuser-&gt;roles </code></pre> <p>But that array doesn't exist.</p> <p>I've traced through the user_load() function in modules/user/user.module with a debugger, and this code should populate the $user object with that roles array:</p> <pre><code> $result = db_query('SELECT * FROM {users} u WHERE '. implode(' AND ', $query), $params); if ($user = db_fetch_object($result)) { $user = drupal_unpack($user); $user-&gt;roles = array(); if ($user-&gt;uid) { $user-&gt;roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user'; } else { $user-&gt;roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user'; } $result = db_query('SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d', $user-&gt;uid); while ($role = db_fetch_object($result)) { $user-&gt;roles[$role-&gt;rid] = $role-&gt;name; } user_module_invoke('load', $user_info, $user); } else { $user = FALSE; } </code></pre> <p>Everything's fine up through this line:</p> <pre><code> $user = drupal_unpack($user); </code></pre> <p>but then, when we hit the next line, which should initialize an empty "roles" array in the $user object, nothing happens:</p> <pre><code> $user-&gt;roles = array(); </code></pre> <p>No "roles" array shows up in the object at all. The subsequent db queries work okay, and return the right role information, so this while loop:</p> <pre><code> while ($role = db_fetch_object($result)) { $user-&gt;roles[$role-&gt;rid] = $role-&gt;name; } </code></pre> <p>has the proper values in $role->rid and $role->name each time through the loop, but $user->roles still doesn't exist, and the assignments here have no effect.</p> <p>I'm beating my head against this - I can't figure out what's going on. I know that I can just query the db directly in order to get a user's roles if I really must, but why wouldn't the user_load() code work?</p> <p>Anyone know what's going on? </p> <p>Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload