public function ImageWidget::formElement in Drupal 10
Same name and namespace in other branches
- 8 core/modules/image/src/Plugin/Field/FieldWidget/ImageWidget.php \Drupal\image\Plugin\Field\FieldWidget\ImageWidget::formElement()
- 9 core/modules/image/src/Plugin/Field/FieldWidget/ImageWidget.php \Drupal\image\Plugin\Field\FieldWidget\ImageWidget::formElement()
File
- core/
modules/ image/ src/ Plugin/ Field/ FieldWidget/ ImageWidget.php, line 142
Class
- ImageWidget
- Plugin implementation of the 'image_image' widget.
Namespace
Drupal\image\Plugin\Field\FieldWidgetCode
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$field_settings = $this
->getFieldSettings();
// Add image validation.
$element['#upload_validators']['file_validate_is_image'] = [];
// Add upload resolution validation.
if ($field_settings['max_resolution'] || $field_settings['min_resolution']) {
$element['#upload_validators']['file_validate_image_resolution'] = [
$field_settings['max_resolution'],
$field_settings['min_resolution'],
];
}
$extensions = $field_settings['file_extensions'];
$supported_extensions = $this->imageFactory
->getSupportedExtensions();
// If using custom extension validation, ensure that the extensions are
// supported by the current image toolkit. Otherwise, validate against all
// toolkit supported extensions.
$extensions = !empty($extensions) ? array_intersect(explode(' ', $extensions), $supported_extensions) : $supported_extensions;
$element['#upload_validators']['file_validate_extensions'][0] = implode(' ', $extensions);
// Add mobile device image capture acceptance.
$element['#accept'] = 'image/*';
// Add properties needed by process() method.
$element['#preview_image_style'] = $this
->getSetting('preview_image_style');
$element['#title_field'] = $field_settings['title_field'];
$element['#title_field_required'] = $field_settings['title_field_required'];
$element['#alt_field'] = $field_settings['alt_field'];
$element['#alt_field_required'] = $field_settings['alt_field_required'];
// Default image.
$default_image = $field_settings['default_image'];
if (empty($default_image['uuid'])) {
$default_image = $this->fieldDefinition
->getFieldStorageDefinition()
->getSetting('default_image');
}
// Convert the stored UUID into a file ID.
if (!empty($default_image['uuid']) && ($entity = \Drupal::service('entity.repository')
->loadEntityByUuid('file', $default_image['uuid']))) {
$default_image['fid'] = $entity
->id();
}
$element['#default_image'] = !empty($default_image['fid']) ? $default_image : [];
return $element;
}