Обработка описание в поле изображения (field WidgetImage)

друпал позволяет создавать свой обработчики полей, но для определённых обработок нету определённых хооков. Для выхода из таких ситуаций программирование на php помогает создавать классы из родителей который наследует все методы. В нашем примере просто нужно обработать описание изображения через другой шаблон темы где у нас будет свой логика но одновременно сохраним логику загрузка изображения от основного модуля

web/modules/image_override/src/Plugin/Field/FieldWidget/ImageOverrideWidget.php

<?php
namespace Drupal\image_override\Plugin\Field\FieldWidget;

use Drupal\Core\Annotation\Translation;
use Drupal\Core\Field\Annotation\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\image\Plugin\Field\FieldWidget\ImageWidget;

/**
 * Plugin implementation of the 'image_override' widget.
 *
 * @FieldWidget(
 *   id = "image_image_override",
 *   label = @Translation("Image Override"),
 *   field_types = {
 *     "image"
 *   }
 * )
 */

class ImageOverrideWidget extends ImageWidget {

  protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
    $elements = parent::formMultipleElements($items, $form, $form_state); // TODO: Change the autogenerated stub

    $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
    $file_upload_help = [
      '#theme' => 'file_upload_help_override',
      '#description' => '',
      '#upload_validators' => $elements[0]['#upload_validators'],
      '#cardinality' => $cardinality,
    ];
    if ($cardinality == 1) {
      // If there's only one field, return it as delta 0.
      if (empty($elements[0]['#default_value']['fids'])) {
        $file_upload_help['#description'] = $this->getFilteredDescription();
        $elements[0]['#description'] = \Drupal::service('renderer')->renderPlain($file_upload_help);
      }
    }
    else {
      $elements['#file_upload_description'] = $file_upload_help;
    }

    return $elements;
  }


}

web/modules/image_override/templates/file-upload-help-override.html.twig

{#
/**
 * @file
 * Default theme implementation to display help text for file fields.
 *
 * Available variables:
 * - descriptions: Lines of help text for uploading a file.
 *
 * @see template_preprocess_file_upload_help_overrode()
 *
 * @ingroup themeable
 */
#}
{{ descriptions|safe_join('<br />') }}

web/modules/image_override/image_override.field.inc

<?php

/**
 * Prepares variables for file upload help text templates.
 *
 * Default template: file-upload-help-override.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - description: The normal description for this field, specified by the
 *     user.
 *   - upload_validators: An array of upload validators as used in
 *     $element['#upload_validators'].
 */
function template_preprocess_file_upload_help_override(&$variables) {
  $description = $variables['description'];
//  $upload_validators = $variables['upload_validators'];
//  $cardinality = $variables['cardinality'];

  $descriptions = [];

  if (!empty($description)) {
    $descriptions[] = \Drupal\Core\Field\FieldFilteredMarkup::create($description);
  }
//  if (isset($cardinality)) {
//    if ($cardinality == -1) {
//      $descriptions[] = t('Unlimited number of files can be uploaded to this field.');
//    }
//    else {
//      $descriptions[] = \Drupal::translation()->formatPlural($cardinality, 'One file only.', 'Maximum @count files.');
//    }
//  }
//  if (isset($upload_validators['file_validate_size'])) {
//    $descriptions[] = t('@size limit.', ['@size' => format_size($upload_validators['file_validate_size'][0])]);
//  }
//  if (isset($upload_validators['file_validate_extensions'])) {
//    $descriptions[] = t('Allowed types: @extensions.', ['@extensions' => $upload_validators['file_validate_extensions'][0]]);
//  }
//
//  if (isset($upload_validators['file_validate_image_resolution'])) {
//    $max = $upload_validators['file_validate_image_resolution'][0];
//    $min = $upload_validators['file_validate_image_resolution'][1];
//    if ($min && $max && $min == $max) {
//      $descriptions[] = t('Images must be exactly <strong>@size</strong> pixels.', ['@size' => $max]);
//    }
//    elseif ($min && $max) {
//      $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels. Images larger than <strong>@max</strong> pixels will be resized.', ['@min' => $min, '@max' => $max]);
//    }
//    elseif ($min) {
//      $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels.', ['@min' => $min]);
//    }
//    elseif ($max) {
//      $descriptions[] = t('Images larger than <strong>@max</strong> pixels will be resized.', ['@max' => $max]);
//    }
//  }

  $variables['descriptions'] = $descriptions;
}

web/modules/image_override/image_override.info.yml

name : "Image Override"
core: 8.x
type: module
dependencies:
  - drupal:file

web/modules/image_override/image_override.module

<?php

/**
 * Implements hook_theme().
 */
function image_override_theme($existing, $type, $theme, $path) {
  return [
    'file_upload_help_override' => [
      'variables' => ['description' => NULL, 'upload_validators' => NULL, 'cardinality' => NULL],
      'file' => 'image_override.field.inc',
    ]
  ];
}

 

Добавление ViewMode переменю для Пользователя
Обработка сущность с сервисами в шаблона Twig (Гибкий обработчик) в Symfony 5
Советую почитать