1

I'd like to display a field_address in a view mode twice, once as the displayed address and once as a google maps directions link. I suppose I could create one custom field formatter that outputs both components, but it seems excessive to create a formatter to display basically what should be two formatters.

Is there a way, say in hook_entity_view to display a field twice with two formatters? Basically say $build['field_address_direction'] = $build['field_address'] and then change the formatter?

  • Have you tried/thought of using Views? – No Sssweat Oct 18 '16 at 23:48
  • It's funny, in this case, I'm already using views, but rendering the node with a view mode. This is for my main search, and not all content types or entities have field_address, although, I like being able to have templates for each entity type. I guess you can do that with views as well, different templates for each content type? At this point, I don't think I would want to do it that way, as I'm 99% there, and I could just do some custom code in hook_entity_view to format the address. I'm just thinking in terms of future development, it would be nice to use a formatter. – oknate Oct 19 '16 at 0:33
2

If you want to display a field twice in hook_ENTITY_TYPE_view(), you can get the field object from the first field and clone the field with a different field formatter and custom display settings.

For example to add the body a second time with the field formatter text_summary_or_trimmed and a custom trim length of 80:

function mymodule_node_view(&$build, $entity, $display, $view_mode) {
  if (isset($build['body']['#items'])) {
    $build['body_teaser'] = $build['body']['#items']->view([
      'type' => 'text_summary_or_trimmed',
      'settings' => [
        'trim_length' => 80,
      ],
    ]);
  }
}

You can clone the current settings this way:

$build['body']['#items']->getSettings();
  • Thanks, I was trying to do this but it wasn't working, it was just returning an array that matched what I was passing into ->view, like this ['type' => 'google_maps_directions'], but I wasn't passing in settings, so maybe that's what I was missing. Let me try again. – oknate Oct 19 '16 at 11:03
  • that was it, I needed to clone the settings. – oknate Oct 19 '16 at 14:51

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.