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.
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 Drupal 7 modules which define entities and who want to invoke this hook should look at this change record for Drupal 7.33 for guidance on how to do so. (The recommended method changed in Drupal 7.33 due to subtle bugs that were present in certain situations when the old method was used. However, the new method requires an API function that was not introduced until Drupal 7.33. To view the old method that was originally recommended here, see the earlier version of this change record [requires a Drupal.org account].)
In Drupal 8, the hook invocation happens by default in EntityViewBuilder::buildContent()
; manual invocation is only necessary if that method is not used.