public static function MediaLibrary::validateItem in Media Library Form API Element 2.x
Same name and namespace in other branches
- 8 src/Element/MediaLibrary.php \Drupal\media_library_form_element\Element\MediaLibrary::validateItem()
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
- src/
Element/ MediaLibrary.php, line 393
Class
- MediaLibrary
- Provides a Media library form element.
Namespace
Drupal\media_library_form_element\ElementCode
public static function validateItem(array $form, FormStateInterface $form_state) {
$button = $form_state
->getTriggeringElement();
$element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -1));
$media = static::getNewMediaItem($element, $form_state);
if (empty($media)) {
return;
}
// Validate that each selected media is of an allowed bundle.
$all_bundles = \Drupal::service('entity_type.bundle.info')
->getBundleInfo('media');
$bundle_labels = array_map(static function ($bundle) use ($all_bundles) {
return $all_bundles[$bundle]['label'];
}, $element['#target_bundles']);
if ($element['#target_bundles'] && !in_array($media
->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
->label(),
'@types' => implode(', ', $bundle_labels),
]));
}
}