You are here

public static function MediaLibraryWidget::validateItems in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/media_library/src/Plugin/Field/FieldWidget/MediaLibraryWidget.php \Drupal\media_library\Plugin\Field\FieldWidget\MediaLibraryWidget::validateItems()
  2. 9 core/modules/media_library/src/Plugin/Field/FieldWidget/MediaLibraryWidget.php \Drupal\media_library\Plugin\Field\FieldWidget\MediaLibraryWidget::validateItems()

Validates that newly selected items can be added to the widget.

Making an invalid selection from the view should not be possible, but we still validate in case other selection methods (ex: upload) are valid.

Parameters

array $form: The form array.

\Drupal\Core\Form\FormStateInterface $form_state: The form state.

File

core/modules/media_library/src/Plugin/Field/FieldWidget/MediaLibraryWidget.php, line 830

Class

MediaLibraryWidget
Plugin implementation of the 'media_library_widget' widget.

Namespace

Drupal\media_library\Plugin\Field\FieldWidget

Code

public static function validateItems(array $form, FormStateInterface $form_state) {
  $button = $form_state
    ->getTriggeringElement();
  $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -1));
  $field_state = static::getFieldState($element, $form_state);
  $media = static::getNewMediaItems($element, $form_state);
  if (empty($media)) {
    return;
  }

  // Check if more items were selected than we allow.
  $cardinality_unlimited = $element['#cardinality'] === FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED;
  $selection = count($field_state['items']) + count($media);
  if (!$cardinality_unlimited && $selection > $element['#cardinality']) {
    $form_state
      ->setError($element, \Drupal::translation()
      ->formatPlural($element['#cardinality'], 'Only one item can be selected.', 'Only @count items can be selected.'));
  }

  // Validate that each selected media is of an allowed bundle.
  $all_bundles = \Drupal::service('entity_type.bundle.info')
    ->getBundleInfo('media');
  $bundle_labels = array_map(function ($bundle) use ($all_bundles) {
    return $all_bundles[$bundle]['label'];
  }, $element['#target_bundles']);
  foreach ($media as $media_item) {
    if ($element['#target_bundles'] && !in_array($media_item
      ->bundle(), $element['#target_bundles'], TRUE)) {
      $form_state
        ->setError($element, t('The media item "@label" is not of an accepted type. Allowed types: @types', [
        '@label' => $media_item
          ->label(),
        '@types' => implode(', ', $bundle_labels),
      ]));
    }
  }
}