0

I have a paragraph type to output a list of content. The editor can set different options, one of them is to show the list as teasers or just node titles linked to node. The corresponding part in code looks like:

    if ($teaser_display) {
      $value = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'teaser');
    }
    else {
      $value = \Drupal::entityTypeManager()->getViewBuilder('node')->viewField($node->get('title'), ['link' => true, 'type' => 'entity_reference_label']);
    }

Is there a way to build the render array for titel field linked to the node without creating a dedicated view mode and without rendering the markup directly? I thought it should somehow work to use the method viewField() as $display_options can either be a view mode or an array with display options.

  • 3
    This formatter is for an entity reference field, so you can use it only on the field in the paragraph type where you reference the node. – 4k4 Apr 29 at 16:13
  • Is there a way/formatter to theme the title as link? Or doesn't it work as title is a basefield an does not have a formatter. I was wrong on view mode, it's also not possible without modifying the template. – LarS Apr 29 at 21:35
  • 1) As said in the comment before, it is possible when you view $paragraph->field_reference with entity_reference_label. 2) Yes, now the title is not configurable in view modes and hardcoded in the node template, but this is going to change. See drupal.org/project/drupal/issues/2353867 – 4k4 Apr 29 at 22:25
  • 2
    I think this ticket can be closed as it is now just about How do I theme a link?. – LarS Apr 29 at 22:29
  • 1
    Not exactly a duplicate. You are rendering this in a paragraph? Then you can't simply build the link like this without including the cache tag '#cache' => ['tags' => $node->getCacheTags()],, which btw. the field formatter on the paragraph field would do. – 4k4 Apr 29 at 22:59
2

As pointed out by @4k4 I used the entity reference field formatter, which does not apply here. Theming as link, as answered in How do I theme a link? does the job:

if ($teaser_display) {
  $value = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'teaser');
}
else {
  $value = [
    '#type' => 'link',
    '#title' => $node->label(),
    '#url' => $node->toUrl(),
    '#cache' => ['tags' => $node->getCacheTags()],
  ];
}

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.