Change record status: 
Project: 
Introduced in branch: 
7.x
Introduced in version: 
7.33
Description: 

Drupal 7.33 introduces a new API function, entity_view_mode_prepare(), which should be used by modules which define entities who want to invoke hook_entity_view_mode_alter() to allow other modules to programmatically alter the view mode when the entity is being displayed.

The hook_entity_view_mode_alter() hook was originally introduced in Drupal 7.17 (see the change record). The code examples that were provided for entity-defining modules in that change record are superseded by the ones in this change record, since they led to some subtle bugs in certain situations. As of Drupal 7.33, the node, user, comment, and taxonomy term entities provided by Drupal core have switched to using the new method below, and it is recommended that contributed module authors do the same.

When displaying a single entity

Look at an example such as user_build_content() (as called by user_view()) for guidance. In particular, the basic pattern (compared to Drupal 7.16 and earlier) is now:

  // NEW CODE:
  // Allow modules to change the view mode.
  $view_mode = key(entity_view_mode_prepare('YOUR_ENTITY_TYPE', array($entity->YOUR_ENTITY_ID_KEY => $entity), $view_mode, $langcode));

....

  // 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);

When displaying multiple entities at once

Look at an example such as node_view_multiple() for guidance. In particular, the basic pattern is:

  1. Call entity_view_mode_prepare() to get an array of entities grouped by view mode.
  2. For each group of entities, call field_attach_prepare_view(), entity_prepare_view(), etc., with the corresponding view mode and entities passed in.
  3. For each entity, get a renderable array for displaying the entity, again using the appropriate view mode.
  4. Make sure the final render array is properly sorted to reflect the order in which the entities were originally passed in to the function.
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
Details: 
Progress: