i have the following problem in Drupal 8.

In custom content type there is a field, which is a multiple entity reference to the same content type. The field is set to use custom view mode, where only title and body fields are displayed. Kind of sub-pages structure. Also the content type has a boolean field, which determines whether the body field of sub pages (entity reference) should be displayed or not. So in my theme_preprocess_field() hook i can get the boolean value, but i don't know how to pass it to the entity references, so in my node--mypage--grid-item.html.twig i could check for that flag and determine should be content.body be rendered or not.

Thank for any hints.

1 Answer 1


Create two view separate modes for your entity reference, one for each boolean value. In preprocessing, modify the view mode of the entity reference depending on the value of the boolean field.

This is a code example I'm using for paragraphs to change the view mode of a referenced media entity:

function mytheme_preprocess_paragraph__image(array &$variables) {
  $paragraph = $variables['paragraph'];

  if ($paragraph->hasField('field_imageratio')) {
    $imageViewMode = str_replace('media.', '', $paragraph->field_imageratio->target_id);
    if (isset($variables['content']['field_image']['0']['#view_mode'])) {
      $variables['content']['field_image']['0']['#view_mode'] = $imageViewMode; 

I think you can largely reuse the logic above, field_imageratio should be replaced by your boolean field, field_image should be replaced by your entity reference field.

  • Thanks for the suggestion, i also had this idea, but the situation i explained is a simplest case, in reality i have 3 flags, which means i have to create 8 view modes ..., will do as a last solution. Commented Dec 5, 2017 at 11:02
  • I don't think it is possible to pass variables between templates. But for your case you could try using HOOK_entity_view_mode_alter($view_mode, $entity) and in there you could code logic based upon $parent_entity = $entity->_referringItem->getEntity();
    – Hudri
    Commented Dec 5, 2017 at 11:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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