3 namespace Drupal\image\Plugin\Field\FieldType;
5 use Drupal\Component\Utility\Random;
6 use Drupal\Core\Field\FieldDefinitionInterface;
7 use Drupal\Core\Field\FieldStorageDefinitionInterface;
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\Core\StreamWrapper\StreamWrapperInterface;
10 use Drupal\Core\TypedData\DataDefinition;
11 use Drupal\file\Entity\File;
12 use Drupal\file\Plugin\Field\FieldType\FileItem;
15 * Plugin implementation of the 'image' field type.
19 * label = @Translation("Image"),
20 * description = @Translation("This field stores the ID of an image file as an integer value."),
21 * category = @Translation("Reference"),
22 * default_widget = "image_image",
23 * default_formatter = "image",
26 * "label" = @Translation("File"),
28 * "target_id", "width", "height"
30 * "require_all_groups_for_translation" = TRUE
33 * "label" = @Translation("Alt"),
34 * "translatable" = TRUE
37 * "label" = @Translation("Title"),
38 * "translatable" = TRUE
41 * list_class = "\Drupal\file\Plugin\Field\FieldType\FileFieldItemList",
42 * constraints = {"ReferenceAccess" = {}, "FileValidation" = {}}
45 class ImageItem extends FileItem {
50 * @var \Drupal\Core\Entity\EntityManagerInterface
52 protected $entityManager;
57 public static function defaultStorageSettings() {
66 ] + parent::defaultStorageSettings();
72 public static function defaultFieldSettings() {
74 'file_extensions' => 'png gif jpg jpeg',
76 'alt_field_required' => 1,
78 'title_field_required' => 0,
79 'max_resolution' => '',
80 'min_resolution' => '',
88 ] + parent::defaultFieldSettings();
90 unset($settings['description_field']);
97 public static function schema(FieldStorageDefinitionInterface $field_definition) {
101 'description' => 'The ID of the file entity.',
106 'description' => "Alternative image text, for the image's 'alt' attribute.",
111 'description' => "Image title text, for the image's 'title' attribute.",
116 'description' => 'The width of the image in pixels.',
121 'description' => 'The height of the image in pixels.',
127 'target_id' => ['target_id'],
131 'table' => 'file_managed',
132 'columns' => ['target_id' => 'fid'],
141 public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
142 $properties = parent::propertyDefinitions($field_definition);
144 unset($properties['display']);
145 unset($properties['description']);
147 $properties['alt'] = DataDefinition::create('string')
148 ->setLabel(t('Alternative text'))
149 ->setDescription(t("Alternative image text, for the image's 'alt' attribute."));
151 $properties['title'] = DataDefinition::create('string')
152 ->setLabel(t('Title'))
153 ->setDescription(t("Image title text, for the image's 'title' attribute."));
155 $properties['width'] = DataDefinition::create('integer')
156 ->setLabel(t('Width'))
157 ->setDescription(t('The width of the image in pixels.'));
159 $properties['height'] = DataDefinition::create('integer')
160 ->setLabel(t('Height'))
161 ->setDescription(t('The height of the image in pixels.'));
169 public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
172 // We need the field-level 'default_image' setting, and $this->getSettings()
173 // will only provide the instance-level one, so we need to explicitly fetch
175 $settings = $this->getFieldDefinition()->getFieldStorageDefinition()->getSettings();
177 $scheme_options = \Drupal::service('stream_wrapper_manager')->getNames(StreamWrapperInterface::WRITE_VISIBLE);
178 $element['uri_scheme'] = [
180 '#title' => t('Upload destination'),
181 '#options' => $scheme_options,
182 '#default_value' => $settings['uri_scheme'],
183 '#description' => t('Select where the final files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
186 // Add default_image element.
187 static::defaultImageForm($element, $settings);
188 $element['default_image']['#description'] = t('If no image is uploaded, this image will be shown on display.');
196 public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
197 // Get base form from FileItem.
198 $element = parent::fieldSettingsForm($form, $form_state);
200 $settings = $this->getSettings();
202 // Add maximum and minimum resolution settings.
203 $max_resolution = explode('x', $settings['max_resolution']) + ['', ''];
204 $element['max_resolution'] = [
206 '#title' => t('Maximum image resolution'),
207 '#element_validate' => [[get_class($this), 'validateResolution']],
209 '#field_prefix' => '<div class="container-inline">',
210 '#field_suffix' => '</div>',
211 '#description' => t('The maximum allowed image size expressed as WIDTH×HEIGHT (e.g. 640×480). Leave blank for no restriction. If a larger image is uploaded, it will be resized to reflect the given width and height. Resizing images on upload will cause the loss of <a href="http://wikipedia.org/wiki/Exchangeable_image_file_format">EXIF data</a> in the image.'),
213 $element['max_resolution']['x'] = [
215 '#title' => t('Maximum width'),
216 '#title_display' => 'invisible',
217 '#default_value' => $max_resolution[0],
219 '#field_suffix' => ' × ',
221 $element['max_resolution']['y'] = [
223 '#title' => t('Maximum height'),
224 '#title_display' => 'invisible',
225 '#default_value' => $max_resolution[1],
227 '#field_suffix' => ' ' . t('pixels'),
230 $min_resolution = explode('x', $settings['min_resolution']) + ['', ''];
231 $element['min_resolution'] = [
233 '#title' => t('Minimum image resolution'),
234 '#element_validate' => [[get_class($this), 'validateResolution']],
236 '#field_prefix' => '<div class="container-inline">',
237 '#field_suffix' => '</div>',
238 '#description' => t('The minimum allowed image size expressed as WIDTH×HEIGHT (e.g. 640×480). Leave blank for no restriction. If a smaller image is uploaded, it will be rejected.'),
240 $element['min_resolution']['x'] = [
242 '#title' => t('Minimum width'),
243 '#title_display' => 'invisible',
244 '#default_value' => $min_resolution[0],
246 '#field_suffix' => ' × ',
248 $element['min_resolution']['y'] = [
250 '#title' => t('Minimum height'),
251 '#title_display' => 'invisible',
252 '#default_value' => $min_resolution[1],
254 '#field_suffix' => ' ' . t('pixels'),
257 // Remove the description option.
258 unset($element['description_field']);
260 // Add title and alt configuration options.
261 $element['alt_field'] = [
262 '#type' => 'checkbox',
263 '#title' => t('Enable <em>Alt</em> field'),
264 '#default_value' => $settings['alt_field'],
265 '#description' => t('The alt attribute may be used by search engines, screen readers, and when the image cannot be loaded. Enabling this field is recommended.'),
268 $element['alt_field_required'] = [
269 '#type' => 'checkbox',
270 '#title' => t('<em>Alt</em> field required'),
271 '#default_value' => $settings['alt_field_required'],
272 '#description' => t('Making this field required is recommended.'),
276 ':input[name="settings[alt_field]"]' => ['checked' => TRUE],
280 $element['title_field'] = [
281 '#type' => 'checkbox',
282 '#title' => t('Enable <em>Title</em> field'),
283 '#default_value' => $settings['title_field'],
284 '#description' => t('The title attribute is used as a tooltip when the mouse hovers over the image. Enabling this field is not recommended as it can cause problems with screen readers.'),
287 $element['title_field_required'] = [
288 '#type' => 'checkbox',
289 '#title' => t('<em>Title</em> field required'),
290 '#default_value' => $settings['title_field_required'],
294 ':input[name="settings[title_field]"]' => ['checked' => TRUE],
299 // Add default_image element.
300 static::defaultImageForm($element, $settings);
301 $element['default_image']['#description'] = t("If no image is uploaded, this image will be shown on display and will override the field's default image.");
309 public function preSave() {
312 $width = $this->width;
313 $height = $this->height;
315 // Determine the dimensions if necessary.
316 if (empty($width) || empty($height)) {
317 $image = \Drupal::service('image.factory')->get($this->entity->getFileUri());
318 if ($image->isValid()) {
319 $this->width = $image->getWidth();
320 $this->height = $image->getHeight();
328 public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
329 $random = new Random();
330 $settings = $field_definition->getSettings();
333 $min_resolution = empty($settings['min_resolution']) ? '100x100' : $settings['min_resolution'];
334 $max_resolution = empty($settings['max_resolution']) ? '600x600' : $settings['max_resolution'];
335 $extensions = array_intersect(explode(' ', $settings['file_extensions']), ['png', 'gif', 'jpg', 'jpeg']);
336 $extension = array_rand(array_combine($extensions, $extensions));
337 // Generate a max of 5 different images.
338 if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= 5) {
339 $tmp_file = drupal_tempnam('temporary://', 'generateImage_');
340 $destination = $tmp_file . '.' . $extension;
341 file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY);
342 if ($path = $random->image(drupal_realpath($destination), $min_resolution, $max_resolution)) {
343 $image = File::create();
344 $image->setFileUri($path);
345 $image->setOwnerId(\Drupal::currentUser()->id());
346 $image->setMimeType(\Drupal::service('file.mime_type.guesser')->guess($path));
347 $image->setFileName(drupal_basename($path));
348 $destination_dir = static::doGetUploadLocation($settings);
349 file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
350 $destination = $destination_dir . '/' . basename($path);
351 $file = file_move($image, $destination, FILE_CREATE_DIRECTORY);
352 $images[$extension][$min_resolution][$max_resolution][$file->id()] = $file;
359 // Select one of the images we've already generated for this field.
360 $image_index = array_rand($images[$extension][$min_resolution][$max_resolution]);
361 $file = $images[$extension][$min_resolution][$max_resolution][$image_index];
364 list($width, $height) = getimagesize($file->getFileUri());
366 'target_id' => $file->id(),
367 'alt' => $random->sentences(4),
368 'title' => $random->sentences(4),
376 * Element validate function for resolution fields.
378 public static function validateResolution($element, FormStateInterface $form_state) {
379 if (!empty($element['x']['#value']) || !empty($element['y']['#value'])) {
380 foreach (['x', 'y'] as $dimension) {
381 if (!$element[$dimension]['#value']) {
382 // We expect the field name placeholder value to be wrapped in t()
383 // here, so it won't be escaped again as it's already marked safe.
384 $form_state->setError($element[$dimension], t('Both a height and width value must be specified in the @name field.', ['@name' => $element['#title']]));
388 $form_state->setValueForElement($element, $element['x']['#value'] . 'x' . $element['y']['#value']);
391 $form_state->setValueForElement($element, '');
396 * Builds the default_image details element.
398 * @param array $element
399 * The form associative array passed by reference.
400 * @param array $settings
401 * The field settings array.
403 protected function defaultImageForm(array &$element, array $settings) {
404 $element['default_image'] = [
405 '#type' => 'details',
406 '#title' => t('Default image'),
409 // Convert the stored UUID to a FID.
411 $uuid = $settings['default_image']['uuid'];
412 if ($uuid && ($file = $this->getEntityManager()->loadEntityByUuid('file', $uuid))) {
413 $fids[0] = $file->id();
415 $element['default_image']['uuid'] = [
416 '#type' => 'managed_file',
417 '#title' => t('Image'),
418 '#description' => t('Image to be shown if no image is uploaded.'),
419 '#default_value' => $fids,
420 '#upload_location' => $settings['uri_scheme'] . '://default_images/',
421 '#element_validate' => [
422 '\Drupal\file\Element\ManagedFile::validateManagedFile',
423 [get_class($this), 'validateDefaultImageForm'],
425 '#upload_validators' => $this->getUploadValidators(),
427 $element['default_image']['alt'] = [
428 '#type' => 'textfield',
429 '#title' => t('Alternative text'),
430 '#description' => t('This text will be used by screen readers, search engines, and when the image cannot be loaded.'),
431 '#default_value' => $settings['default_image']['alt'],
434 $element['default_image']['title'] = [
435 '#type' => 'textfield',
436 '#title' => t('Title'),
437 '#description' => t('The title attribute is used as a tooltip when the mouse hovers over the image.'),
438 '#default_value' => $settings['default_image']['title'],
439 '#maxlength' => 1024,
441 $element['default_image']['width'] = [
443 '#value' => $settings['default_image']['width'],
445 $element['default_image']['height'] = [
447 '#value' => $settings['default_image']['height'],
452 * Validates the managed_file element for the default Image form.
454 * This function ensures the fid is a scalar value and not an array. It is
455 * assigned as a #element_validate callback in
456 * \Drupal\image\Plugin\Field\FieldType\ImageItem::defaultImageForm().
458 * @param array $element
459 * The form element to process.
460 * @param \Drupal\Core\Form\FormStateInterface $form_state
463 public static function validateDefaultImageForm(array &$element, FormStateInterface $form_state) {
464 // Consolidate the array value of this field to a single FID as #extended
465 // for default image is not TRUE and this is a single value.
466 if (isset($element['fids']['#value'][0])) {
467 $value = $element['fids']['#value'][0];
468 // Convert the file ID to a uuid.
469 if ($file = \Drupal::entityManager()->getStorage('file')->load($value)) {
470 $value = $file->uuid();
476 $form_state->setValueForElement($element, $value);
482 public function isDisplayed() {
483 // Image items do not have per-item visibility settings.
488 * Gets the entity manager.
490 * @return \Drupal\Core\Entity\EntityManagerInterface
492 protected function getEntityManager() {
493 if (!isset($this->entityManager)) {
494 $this->entityManager = \Drupal::entityManager();
496 return $this->entityManager;