function hook_entity_view_mode_alter

You are here

7 system.api.php hook_entity_view_mode_alter(&$view_mode, $context)
8 entity.api.php hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context)

Change the view mode of an entity that is being displayed.

Parameters

string $view_mode: The view_mode that is to be used to display the entity.

array $context: Array with contextual information, including:

  • entity_type: The type of the entity that is being viewed.
  • entity: The entity object.
  • langcode: The langcode the entity is being viewed in.

Related topics

1 function implements hook_entity_view_mode_alter()

Note: this list is generated by pattern matching, so it may include some functions that are not actually implementations of this hook.

node_test_entity_view_mode_alter in modules/node/tests/node_test.module
Implements hook_entity_view_mode_alter().

File

modules/system/system.api.php, line 480
Hooks provided by Drupal core and the System module.

Code

function hook_entity_view_mode_alter(&$view_mode, $context) {
  // For nodes, change the view mode when it is teaser.
  if ($context['entity_type'] == 'node' && $view_mode == 'teaser') {
    $view_mode = 'my_custom_view_mode';
  }
}

Comments

There seems to be some sort of conflict with the context module as I loose my node contexts when setting $view_mode.

I discovered that, more specifically, the "node type" condition in context is ignored when $view_mode is set in hook_entity_view_mode_alter(). Everything else seems to work.