You are here

function focal_point_form_media_library_add_form_upload_alter in Focal Point 8

Implements hook_form_FORM_ID_alter().

File

./focal_point.module, line 117
Allow users to specify a focal point on content images.

Code

function focal_point_form_media_library_add_form_upload_alter(array &$form, FormStateInterface $form_state) {

  // Get any media items that are in the process of being added.
  // @see \Drupal\media_library\Form\AddFormBase::getAddedMediaItems().
  $media = $form_state
    ->get('media') ?: [];

  /** @var \Drupal\media\MediaInterface $item */
  foreach ($media as $delta => $item) {
    $element =& $form['media'][$delta]['fields'];

    // As a kindness to alter hooks like this one, Media Library includes the
    // name of the source field in the form structure.
    // @see \Drupal\media_library\Form\AddFormBase::buildEntityFormElement()
    $source_field = $element['#source_field_name'];

    // If the source field is configured to use Focal Point, add a #process
    // callback which replaces the static preview thumbnail with the Focal Point
    // widget.
    $component = \Drupal::service('entity_display.repository')
      ->getFormDisplay('media', $item
      ->bundle(), 'media_library')
      ->getComponent($source_field);
    if ($component && $component['type'] === 'image_focal_point' && isset($element[$source_field])) {
      $element[$source_field]['widget'][0]['#process'][] = '_focal_point_replace_media_library_preview';
    }
  }
}