You can do that using views, following the steps to display only the nodes referencing the current user:
- Add a relationship to your field: Entity Reference: Referenced Entity A bridge to the User entity that is referenced via field_your_reference_field
- Add a filter criteria User: Current and select as Relationship the newly added relationship, which should be automatically selected if you don't have any other relationships in your view. Select the radio button Yes.
UPDATE:
As I read your question again, I saw you want to restrict the access, as well. There are many ways to achieve that. You may do that with Rules or using node access grants hook_node_access_records()
and hook_node_grants()
.
If you need instructions on how to use node access grants, I can improve my answer. Otherwise, the solution with rules is already described by Niall Murphy.
UPDATE 2: Using node access grants
If you choose to use node access grants, then you don't need to do above filter on views. Since, views already respects the node access grants and filters the nodes readily.
You need to implement two functions in your custom module: hook_node_access_records()
and hook_node_grants()
.
/**
* Implements hook_node_access_records().
*/
function YOURMODULE_node_access_records($node) {
$grants = array();
if ($node->type == 'YOUR_CONTENT_TYPE') {
$referenced_uid = $node->field_your_reference_field['und'][0]['target_id'];
$grants[] = array(
'realm' => 'YOUR_CONTENT_TYPE_referenced_user', // The naming of the realm is up to you.
'gid' => $referenced_uid,
'grant_view' => 1,
'grant_update' => 0,
'grant_delete' => 0,
);
}
return $grants;
}
/**
* Implements hook_node_grants().
*/
function YOURMODULE_node_grants($account, $op) {
$grants['YOUR_CONTENT_TYPE_referenced_user'] = array($account->uid);
return $grants;
}
Explanation of the above code:
The first function is called on saving the node and puts the node into a realm named YOUR_CONTENT_TYPE_referenced_user
and gives it a Grant Id as the referenced user's uid.
Second function is called on every page call, so it is important not to do any heavy calculations on this part. This function gives the user the grant Id same as his user Id on the same realm. So that this user can view all nodes in that realm with a Grant Id equals to his user Id.