I have a content type with multiple fields. Some of the fields are accessible to everyone and there are other fields for which the access is controlled.

Example: There is a content type called Reports with fields like title, summary, body etc. Title and summary should be visible to everyone but the access to body field is controlled.

For implementing this I need to have 2 view modes. one of them will have the fields title and summary displayed with the rest of the fields hidden. The other view mode will have only the body field visible. I am planning to implement the hook hook_node_access to derive the access permissions for the node. So how can I get the view mode in this hook so that I can have my access check based on the view mode.


3 Answers 3


I did some searches but I couldn't find any module that does this. But you can implement the hook_node_view() like this:

function YOUR_MODULE_node_view($node, $view_mode, $langcode) {
    global $user;
    //verify that the user is not loged and the view mode is full view
    if(in_array('anonymous user', $user->roles) && $view_mode == 'full') {
        //denied the access
        //avoids other hooks are invoked

I tested the above code and it works.


In Drupal 7 you can use Field Permissions module

The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

  • In my case the access permissions are not based on user role. The access is specified at the user level and it is controlled using custom code. So I dont think Field Permissions module helps my case.
    – Bhuvana
    May 26, 2014 at 10:57

In Drupal 8+

 * Implements hook_node_view().
 * @param array $build
 * @param \Drupal\Core\Entity\EntityInterface $entity
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
 * @param $view_mode
function YOUR_MODULE_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  $displayId = $display->id();
  if ($displayId === 'node.YOUR_NODE_TYPE.default') {
    $roles = \Drupal::currentUser()->getRoles();
    if (!in_array('administrator', $roles, TRUE)) {
      throw new AccessDeniedHttpException();
  • Replace YOUR_MODULE with your module machine name.
  • Replace YOUR_NODE_TYPE with the machine name of the content type.
  • Add use statements for the entity and display classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.