ADVERTISEMENT

Drupal - Alter field value before render

It's too late to change the field object, because the field is already prepared for rendering. You have to find the field value inside of the render array, for example in #markup, and change it there. Where you find the value depends how your field display is configured in the view mode.

While possible, there's often a better way. You could make your own formatter that returns the structure that you want. #text is a formatted text field, you could make a filter that transforms the text the way you want. Depends on what you want to do exactly.

(Comment from @Berdir)

See the drupal docs how to create a custom field formatter:

https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-field-formatter


As above mentioned you have to alter the #markup, example for field "field_block_iframe" below:

/**
 * Implements hook_preprocess_field().
 *
 * @param $variables
 * @param $hook
 */
function THEME_preprocess_field__field_block_iframe(&$variables, $hook) {
  $variables['items'][0]['content']['#markup'] = 'Going down, to the core.';
}