Applying node access on a non-node based view

Node access is only enforced when the views base table is {node}. This is an example of listing field collections and joining the node access table. This is taken fromĀ http://kybest.hu/en/blog/applying-node-access-on-a-non-node-based-view

The Views module automatically joins the node_access table only for node based views. In any other case we need to take care of the proper access handling ourselves.

Using Views we were listing field_collections attached to nodes.These few lines of code solved joining the node_access table properly:

/**
 * Implements hook_query_TAG_alter().
 */
function MYMODULE_query_views_MYVIEWNAME_alter($query) {
  // Add a node_access join to a field_collection view.
  $query->addTag('node_access')->addMetaData('base_table', 'field_data_MYFIELDCOLLECTIONNAME');
  _node_query_node_access_alter($query, 'entity');
}

Explanation:

MYMODULE is the name of the module implementing the hook.
MYVIEWNAME is the machine name of the view.
The hook runs because every views query gets the views_MYVIEWNAME tag.
MYFIELDCOLLECTIONNAME is the machine name of the field collection field on the node.
Due to the 'entity' argument of the _node_query_node_access_alter($query, 'entity'); call the 'field_data_MYFIELDCOLLECTIONNAME' table will be joined to the node_access table through its 'entity_id' column. If we have a 'nid' column then we should use 'node' instead of 'entity'.

Tags

Internal References

External References

Article Type

General