8

I added a Node-reference field (machine name: field_node) to all users at:

example.com/admin/config/people/accounts/fields/

I am now working in a custom module & hook_node_access

How do I access the Node-reference field programmatically when the user is logged in?

10

You can get field values from any entity with field_get_items(); the logged in user is available in the global $user object, and to load fields onto that object you can use user_load().

Put those together and you get something like this:

// Get a fully loaded entity object for the logged in user.
$account = user_load($GLOBALS['user']->uid);

// Extract the field items
$field_items = field_get_items('user', $account, 'field_node');
if ($field_items) {
  // This will be 'target_id' if you're using the Entity Reference module, 
  // or 'nid' if you're using References
  $column_name = '?'; 

  $nid = $field_items[0][$column_name];
}

That's the abstract code if you like.

It's worth bearing in mind that hook_node_access() is passed an $account object already (which will be the logged in user if the access check is happening for them) so you would probably be better off using that to check against. You might still need to run it through user_load(), it'll be easy enough to check that with a bit of debugging.

| improve this answer | |
6

Two options here, using core API or entity_metadata_wrapper

global $user;
// Load full user account object
$account = user_load($user->uid);
// Get field;
$items = field_get_items('user', $account, 'field_node');
// Debug info
drupal_set_message('<pre>'.var_export($items,1).'</pre>');
// This gets the sanitized output, from the first field delta value (0)
$output = field_view_value('user', $account, 'field_node', $items[0]);

Relevant functions:

You can also, if using the Entity API module, use entity_metadata_wrapper

global $user;
$user_wrapper = entity_metadata_wrapper('user', $user);
drupal_set_message('<pre>'.var_export($user_wrapper->field_node->raw(),1).'</pre>'); // Raw value
drupal_set_message('<pre>'.var_export($user_wrapper->field_node->value(),1).'</pre>'); // Loaded value

EDIT: Sorry, answer was posted while I was posting this answer.

| improve this answer | |

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.