Changing the view mode of EntityReferenceFieldItems programmatically I have a paragraph (I'm using the Paragraphs module) that contains an entity reference field that contains references to other pages.

The display settings are set to use a particular view mode, e.g. teaser. This renders an teaser image, title and link to the page.

I would like the editor to be able to set the view mode on a per-paragraph basis. I have created a "view mode" field in the paragraph with two options: teaser, and teaser-text-only.

How can I use the view mode set in the "parent" entity (the paragraph) to add a template suggestion when rendering the "child" entities (the pages)?
At this point it should be no problem to change the view mode in the render element of the referenced node. The node has yet to be built and will, hopefully, use the modified view mode.

You can try something like this in a paragraph preprocess hook:

function mytheme_preprocess_paragraph(&amp;$variables) {

  if ($variables['paragraph']-&gt;hasField('field_view_mode')) {
    $view_mode = $variables['paragraph']-&gt;field_view_mode-&gt;value;
    if (isset($variables['content']['field_ref_node']['0']['#view_mode'])) {
      $variables['content']['field_ref_node']['0']['#view_mode'] = $view_mode;
      unset($variables['content']['field_ref_node']['0']['#cache']['keys']);
    }
  }

}


Edit:

To prevent that the node gets cached on it's own in the wrong view mode remove the cache key.