Drupal 10: Change The View Mode Of An Entity

Use this to enforce a particular view mode or to test your view modes.

<?php

use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_view_mode_alter().
 */
function MYMODULE_entity_view_mode_alter(&$view_mode, EntityInterface $entity, $context) {
  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'news' && $view_mode == 'full') {
    $view_mode = 'some_different_view_mode';
  }
}

Useful when you are creating a "search index" view mode and want to make sure it renders correctly.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
4 + 6 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.