In Drupal 7 I did something like:

  function mymodule_views_pre_render(&$view) {
    if ($view->name == 'services') {
      $view->style_plugin->row_plugin->options['view_mode'] = variable_get('services_teaser');
    else if ($view->name == 'portfolio') {
      $view->style_plugin->row_plugin->options['view_mode'] = variable_get('portfolio_teaser');

I don't know how to set the view mode on the fly, in Drupal 8. The idea is to be able to select the view mode for the view from a configuration form, instead of doing it from the view form.

How do I achieve this?


You can select VIew Mode as:

function YOUR_MODULE_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  if ($entity->getEntityTypeId() == 'taxonomy_term' && $entity->bundle() == 'tag' && $view_mode == 'full') {
    $view_mode = 'CUSTOM VIEW MODE';
  • I did not know this existed and I am now very pumped about having it in my toolkit. – Lester Peabody Oct 23 '19 at 16:08

If you have an entity reference field attached to a node, and want to offer the editor a choice of view modes through another field, you can change the view mode in the render array.

In this example my_content_type has a field field_my_entity_reference that is set up to be rendered using default_view_mode. The field_list_style field offers a list of display options that are used to override the default view mode.

function HOOK_entity_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if ($entity->getType() === 'my_content_type') {
    // Get the value of the "setting" field.
    switch ($entity->field_list_style->value) {
      case 'custom':
        // Set the view mode.
        $count = $build['field_my_entity_reference']['#items']->count();
        for ($i = 0; $i < $count; $i++) {
          $build['field_my_entity_reference'][$i]['#view_mode'] = '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.