1

Using the Group module, when a user views a group, I want to use a different view mode depending on whether the user is a member of the group or not.
Conceptually, this is almost identical to showing a different view mode of a node depending on the user role.

I'd have thought it was easy, but I'm struggling. What I know:

  • The route is entity.group.canonical
  • I can modify the result of that route using alterRoutes() in a route subcriber

    protected function alterRoutes(RouteCollection $collection) {
      if ($route = $collection->get('entity.group.canonical')) {
        // Do something.
      }
    }
    

I'm not sure how to modify the route. Swapping in a whole new custom controller seems extreme.

2

Turns out, there's a hook for that.

function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {

  // For nodes, change the view mode when it is teaser.
  if ($entity->getEntityTypeId() == 'node' && $view_mode == 'teaser') {
    $view_mode = 'my_custom_view_mode';
  }
}

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.