1

I would like to change the display mode only for entity.node.canonical, so that a logged-in user would see something completely different than anonymous users.

For example, an entity displayed by an entity reference field should be displayed in teaser mode for anonymous users, and in full mode for logged-in users.

How can I achieve this?

2

This is similar to How do I change the node view mode before rendering?, only that you want to add conditions for the route name and the current user:

/**
 * Implements hook_entity_view_mode_alter().
 */
function mymodule_entity_view_mode_alter(&$view_mode, $entity, $context) {
  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'article') {
    if (\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical') {
      if (\Drupal::currentUser()->isAnonymous()) {
        $view_mode = 'teaser';
      }
    }
  }
}
  • you should also check that the node is the one from the route, this would also change the view mode of any node displays through a reference field or view on another node – Berdir Jul 2 '18 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.