Download & Extend

Added hook_entity_view_mode_alter() to allow modules to change entity view modes on display

Project: 
Drupal core
Introduced in branch: 
7.x, 8.x
Introduced in version: 
7.17
Description: 

Drupal 7.17 introduces a new hook, hook_entity_view_mode_alter(), which allows modules to programmatically alter the view mode when an entity is being displayed.

<?php
function mymodule_entity_view_mode_alter(&$view_mode, $context) {
 
// Change the view mode to teaser for anonymous users viewing a node.
 
if ($context['entity_type'] == 'node' && user_is_anonymous()) {
   
$view_mode = 'teaser';
  }
}
?>

The hook also exists in Drupal 8 except that there is no entity_type argument. Use $context['entity']->entityType() instead.

Module authors should be aware that because this is a new hook, not all entities may actually invoke it on display. (Currently in Drupal core, it is invoked for the node, user, comment, and taxonomy term entities.)

Authors of modules which define entities who want to invoke this hook can look at an example such as user_build_content() (as called by user_view()) for guidance. In particular, the basic pattern is:

<?php
 
// NEW CODE:
  // Allow modules to change the view mode.
 
$context = array(
   
'entity_type' => 'YOUR_ENTITY_TYPE',
   
'entity' => $entity,
   
'langcode' => $langcode,
  );
 
drupal_alter('entity_view_mode', $view_mode, $context);

....

 
// EXISTING CODE:
  // Call standard field and entity view functions and invoke standard hooks
  // (e.g., field_attach_prepare_view(), entity_prepare_view(), hook_entity_view()).

....

 
// NEW CODE:
  // Make sure the current view mode is stored if no module has already
  // populated the related key.
 
$entity->content += array('#view_mode' => $view_mode);
?>

In Drupal 8, the hook invocation happens in by default in EntityRenderController::buildContent(); manual invocation is only necessary if that method is not used.

Impacts: 
Module developers
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done
nobody click here