You are here

public static function ImageWidget::process in Panopoly 8.2

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

modules/panopoly/panopoly_media/src/Plugin/Field/FieldWidget/ImageWidget.php, line 19

Class

ImageWidget
Class ImageWidget.

Namespace

Drupal\panopoly_media\Plugin\Field\FieldWidget

Code

public static function process($element, FormStateInterface $form_state, $form) {
  $element = parent::process($element, $form_state, $form);
  $entityType = $element['#entity_type'];

  // Only deal with media entities for now.
  if ($entityType != 'media') {
    return $element;
  }

  // If we've got files, use the first one.
  if (!empty($element['#files'])) {
    $files = $element['#files'];

    /** @var \Drupal\file\Entity\File $file */
    $file = reset($files);

    // Add IPTC handling to form.
    $iptc = self::getDataService()
      ->getData($file
      ->getFileUri());
    $iptc['name'] = empty($iptc['title']) ? $file
      ->getFilename() : $iptc['title'];
    $parents = array_slice($element['#parents'], 0, -2);

    // Allow JS processing.
    $element['#attached']['library'][] = 'panopoly_media/img_data';
    $element['panopoly_media_img_data'] = [
      '#type' => 'container',
      '#attributes' => [
        'data-type' => [
          'panopolyMediaImgData',
        ],
        'data-entity-type' => $entityType,
        'data-form-parents' => $parents,
      ],
    ];
    foreach (array_filter($iptc) as $property => $value) {
      $element['panopoly_media_img_data']['#attributes']['data-iptc-' . $property] = $value;
    }
    $map = static::getDataService()
      ->getElementMap($entityType);
    $element['#attached']['drupalSettings']['panopolyMediaImgDataMap'][$entityType] = $map;

    // Allow the IPTC values to be altered.
    static::getModuleHandler()
      ->alter('panopoly_media_iptc_values', $iptc, $entityType);

    // Set IPTC data onto the backend form handling.
    foreach ($map as $mapData) {
      if (isset($mapData['element']) && !empty($iptc[$mapData['iptc']])) {

        // Set directly into the widget's element.
        $name = array_merge($mapData['element'], [
          '#default_value',
        ]);
        $val = NestedArray::getValue($element, $name);
        if (empty($val)) {
          NestedArray::setValue($element, $name, $iptc[$mapData['iptc']]);
        }
      }
    }
  }
  return $element;
}