You are here

public static function ImageFieldTokensWigdet::process in ImageField Tokens 8.2

Same name and namespace in other branches
  1. 8 src/Plugin/Field/FieldWidget/ImageFieldTokensWigdet.php \Drupal\imagefield_tokens\Plugin\Field\FieldWidget\ImageFieldTokensWigdet::process()

Form API callback: Processes a image_image field element.

Expands the image_image type to include the alt and title fields.

This method is assigned as a #process callback in formElement() method.

Overrides ImageWidget::process

File

src/Plugin/Field/FieldWidget/ImageFieldTokensWigdet.php, line 168

Class

ImageFieldTokensWigdet
Plugin implementation of the 'image_image' widget.

Namespace

Drupal\imagefield_tokens\Plugin\Field\FieldWidget

Code

public static function process($element, FormStateInterface $form_state, $form) {
  $entity_type = '';
  $current_entity = NULL;
  $field_settings = [];

  // Get form object to retrieve parent entity.
  $form_object = $form_state
    ->getFormObject();
  $get_entity = method_exists($form_object, 'getEntity');
  if ($get_entity) {
    $current_entity = $form_object
      ->getEntity();
    if (!empty($current_entity)) {

      // Get entity data.
      $entity_type = $current_entity
        ->getEntityTypeId();
      $entity_bundle = $current_entity
        ->bundle();

      // Get field settings.
      $field_name = $element['#field_name'];
      $field_config = FieldConfig::loadByName($entity_type, $entity_bundle, $field_name);
      $field_settings = $field_config
        ->getSettings();
    }
  }
  $item = $element['#value'];
  $item['fids'] = $element['fids']['#value'];
  $alt_token = '';
  $title_token = '';

  // Fill alt & title fields from default image settings if they are empty.
  $condition = !empty($field_settings) && !empty($field_settings['default_image']) && (empty($item['alt']) || empty($item['title'])) && (!empty($element['#default_value']['display']) || empty($element['#default_value']['alt']));
  if ($condition) {
    $item['alt'] = $field_settings['default_image']['alt'];
    $item['title'] = $field_settings['default_image']['title'];
  }
  $element['#theme'] = 'image_widget';

  // Add the image preview.
  if (!empty($element['#files']) && $element['#preview_image_style']) {
    $file = reset($element['#files']);
    $variables = [
      'style_name' => $element['#preview_image_style'],
      'uri' => $file
        ->getFileUri(),
    ];

    // Determine image dimensions.
    if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
      $variables['width'] = $element['#value']['width'];
      $variables['height'] = $element['#value']['height'];
    }
    else {
      $image = \Drupal::service('image.factory')
        ->get($file
        ->getFileUri());
      if ($image
        ->isValid()) {
        $variables['width'] = $image
          ->getWidth();
        $variables['height'] = $image
          ->getHeight();
      }
      else {
        $variables['width'] = $variables['height'] = NULL;
      }
    }
    $element['preview'] = [
      '#weight' => -10,
      '#theme' => 'image_style',
      '#width' => $variables['width'],
      '#height' => $variables['height'],
      '#style_name' => $variables['style_name'],
      '#uri' => $variables['uri'],
    ];

    // Store the dimensions in the form so the file doesn't have to be
    // accessed again. This is important for remote files.
    $element['width'] = [
      '#type' => 'hidden',
      '#value' => $variables['width'],
    ];
    $element['height'] = [
      '#type' => 'hidden',
      '#value' => $variables['height'],
    ];
  }
  elseif (!empty($element['#default_image'])) {
    $default_image = $element['#default_image'];
    $file = File::load($default_image['fid']);
    if (!empty($file)) {
      $element['preview'] = [
        '#weight' => -10,
        '#theme' => 'image_style',
        '#width' => $default_image['width'],
        '#height' => $default_image['height'],
        '#style_name' => $element['#preview_image_style'],
        '#uri' => $file
          ->getFileUri(),
      ];
    }
  }
  if (isset($item['alt'])) {
    $alt_token = \Drupal::token()
      ->replace($item['alt'], [
      $entity_type => $current_entity,
    ]);
    if (empty($alt_token)) {
      $alt_token = $item['alt'];
    }
  }
  if (isset($item['title'])) {
    $title_token = \Drupal::token()
      ->replace($item['title'], [
      $entity_type => $current_entity,
    ]);
    if (empty($title_token)) {
      $title_token = $item['title'];
    }
  }

  // Add the additional alt and title fields.
  $element['alt'] = [
    '#title' => new TranslatableMarkup('Alternative text'),
    '#type' => 'textfield',
    '#default_value' => $alt_token ?? '',
    '#description' => new TranslatableMarkup('This text will be used by screen readers, search engines, or when the image cannot be loaded.'),
    // @see https://www.drupal.org/node/465106#alt-text
    '#maxlength' => 512,
    '#weight' => -12,
    '#access' => (bool) $item['fids'] && $element['#alt_field'],
    '#required' => $element['#alt_field_required'],
    '#element_validate' => $element['#alt_field_required'] === 1 ? [
      [
        get_called_class(),
        'validateRequiredFields',
      ],
    ] : [],
  ];
  $element['title'] = [
    '#type' => 'textfield',
    '#title' => new TranslatableMarkup('Title'),
    '#default_value' => $title_token ?? '',
    '#description' => new TranslatableMarkup('The title is used as a tool tip when the user hovers the mouse over the image.'),
    '#maxlength' => 1024,
    '#weight' => -11,
    '#access' => (bool) $item['fids'] && $element['#title_field'],
    '#required' => $element['#title_field_required'],
    '#element_validate' => $element['#title_field_required'] === 1 ? [
      [
        get_called_class(),
        'validateRequiredFields',
      ],
    ] : [],
  ];
  $element['#value']['alt'] = $alt_token;
  $element['#value']['title'] = $title_token;
  return $element;
}