How to use hook_field_preprocess to add a prefix/suffix to an entity reference field for different view modes? 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(&amp;$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?
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' =&gt; ['#markup' =&gt; $prefix],
  'content' =&gt; $variables['items'][0]['content'],
  'suffix' =&gt; ['#markup' =&gt; $suffix],
];