One of the great things about Drupal 7 is that you're able to create fields for Users rather than having to use Content Profile like in Drupal 6. With this the user object becomes much more useful as you don't have load the node associated with that user as the user object contains all the information straight away!
However one issue I've seen people come across is using 'global $user' to try and access the users fields. Loading the global $user object doesn't include data from other modules, including the profile module - so any field assosiated with the user object wont get loaded.
For this example I'm going to add the field 'field_favourite_football_team' to the user in account settings - and see how global $user and user_load() handle this.
Here is an example, first of global $user:
stdClass Object ( [uid] => 1 [name] => James Davidson [pass] => $S$D8XB6QGZTf4.VzbjHF7dtProS5ckKpy8.QfTrrea4PZPwd2DBPnW [mail] => [email protected] [theme] => [signature] => [signature_format] => filtered_html [created] => 1319704879 [access] => 1319705398 [login] => 1319705000 [status] => 1 [timezone] => Europe/London [language] => [picture] => 0 [init] => [email protected] [data] => Array ( [overlay] => 1 ) [sid] => FsAcTpfYlMEU4wo-37Cc_auT-iLFqBRw7j2kepYH5uI [ssid] => [hostname] => 127.0.0.1 [timestamp] => 1319705399 [cache] => 0 [session] => batches|a:1:{i:1;b:1;} [roles] => Array ( [2] => authenticated user [3] => administrator ) )
And then of user_load()
stdClass Object ( [uid] => 1 [name] => James Davidson [pass] => $S$D8XB6QGZTf4.VzbjHF7dtProS5ckKpy8.QfTrrea4PZPwd2DBPnW [mail] => [email protected] [theme] => [signature] => [signature_format] => filtered_html [created] => 1319704879 [access] => 1319705398 [login] => 1319705000 [status] => 1 [timezone] => Europe/London [language] => [picture] => [init] => [email protected] [data] => Array ( [overlay] => 1 ) [roles] => Array ( [2] => authenticated user [3] => administrator ) [field_favourite_football_team] => Array ( [und] => Array ( [0] => Array ( [value] => Manchester City [format] => [safe_value] => Manchester City ) ) ) [rdf_mapping] => Array ( [rdftype] => Array ( [0] => sioc:UserAccount ) [name] => Array ( [predicates] => Array ( [0] => foaf:name ) ) [homepage] => Array ( [predicates] => Array ( [0] => foaf:page ) [type] => rel ) ) )
As you can see using user_load() provides you with the full user object and global $user only gives you a basic user object.
- Log in to post comments