I'm trying to move some markup from twig templates to hook_preprocess_field().

I have an entity reference field (media image) that I want to add a prefix and suffix to.

I added a prefix and suffix like this:

function MYMODULE_preprocess_field__MYFIELD(&$variables) {
  $prefix = 'Hi... ';
  $view_mode = $variables['element']['#view_mode'];
  if ($view_mode == 'second_view_mode') {
    $prefix = 'Hello... ';
  $suffix = '... there.';
  $variables['items'][0]['content']['#prefix'] = $prefix;
  $variables['items'][0]['content']['#suffix'] = $suffix;

With this code, my prefix and suffix get added, but they are cached, and the same for all view modes.

If I rebuild the cache and visit a node in second_view_mode, then I see Hello... as the prefix for all instances of the field. But if I rebuild the cache and visit a node not in second_view_mode, then I see Hi... for all instances of the field, even those on a node in second_view_mode.

I use this same approach/code for formatted text fields and I don't experience this caching problem. So I think I need to do something different for this entity reference field, but I don't know what to do.

How do I add a prefix/suffix to an entity reference field in a preprocess function for different view modes?


1 Answer 1


If you have configured the reference field to render the referenced entities then the build array usually contains #cache keys, which result in a separate cache entry for this render array including anything you've attached to it in preprocess. This has nothing to do with the view mode of the parent entity, the cached result will also be reused when the media is displayed in a different entity.

You could split up the field content in multiple render elements so that you have the prefix/suffix outside of the cached element content:

$variables['items'][0]['content'] = [
  'prefix' => ['#markup' => $prefix],
  'content' => $variables['items'][0]['content'],
  'suffix' => ['#markup' => $suffix],

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.