There are two new hooks added in Drupal 7.17 core, which is scheduled to be released on 7 November 2012.


Introduced in Branch: 7.x, 8.x
Introduced in version: 7.17

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.

We 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.)

Modules which define entities and 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);
?>

Tags: 

Post new comment