I have a text field in a media image type (for a photo caption) - I'd like to output a default value whenever it's empty.

I tried using HOOK_preprocess_field, but that hook isn't reached if the field of the node is blank.

It's being inserted in a View, but it's more than one field (a display mode of a Rendered Entity showing a photo thumbnail and the caption) and therefore as the photo is present when the caption isn't, I can't use the No results behaviour.

I also tried HOOK_preprocess_node and HOOK_preproces_content_field, neither of those seem to be called at all in the view.

Is there anywhere else I can edit it?

  • 1
    The text fiels is in the media image so i thinks the hook theme_preprocess_media is the right one
    – berramou
    Sep 25, 2019 at 19:10
  • @berramou thanks - yes, it's that hook, I can rewrite populated fields by changing [0]['#context']['value'], unfortunately $variables['content']['field_caption'] has almost nothing in it for the blank field - I've just spent ages trying to manually recreate all the fields in the array, but I then get Call to a member function getFieldDefinition() on null in quickedit_preprocess_field(), not sure if there's a method I could use to do it properly? Sep 25, 2019 at 20:22

2 Answers 2


You might consider overriding an appropriate Twig template, something along the lines of {% if content.field_caption %} {{ content.field_caption }} {% else %}} default text {% endif %}


You can use the hook theme_preprocess_media check on media if it's an image and than get the default value of your field to compare it with the actual value.
Try the following.

 * Implements hook_preprocess_HOOK().
function myTheme_preprocess_media(&$variables) {
  /** @var \Drupal\media\MediaInterface $media */
  $media = $variables['media'];
  if ($media->getSource()->getPluginId() === 'image') {
    $elements = $variables['elements'];
    if ($media->hasField('field_caption') && isset($elements['field_caption'])) {
      // Get the default value of field_caption field.
      // To compare it with the the actual value.
      $caption_default_value = $elements['field_caption']['#items']->first()
      // Get the actual value.
      $caption_actual_value = $media->field_caption->getValue()[0]['value'];

      // Check if the value hasn't change so its has the default value.
     if ($caption_default_value === $caption_actual_value){
       // Change the value of caption  field.
       $variables['content']['field_caption'][0]['#context']['value'] = t('This is new value of caption');

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.