image.field.inc 2.13 KB
Newer Older
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Implement an image field, based on the file module's file field.
 */

8
use Drupal\Core\Render\Element;
9

10
/**
11 12 13
 * Prepares variables for image widget templates.
 *
 * Default template: image-widget.html.twig.
14
 *
15
 * @param array $variables
16 17
 *   An associative array containing:
 *   - element: A render element representing the image field widget.
18
 */
19
function template_preprocess_image_widget(&$variables) {
20 21
  $element = $variables['element'];

22
  $variables['attributes'] = ['class' => ['image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix']];
23

24 25
  if (!empty($element['fids']['#value'])) {
    $file = reset($element['#files']);
26
    $element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
27 28
  }

29
  $variables['data'] = [];
30 31 32 33
  foreach (Element::children($element) as $child) {
    $variables['data'][$child] = $element[$child];
  }

34 35 36
}

/**
37 38 39
 * Prepares variables for image formatter templates.
 *
 * Default template: image-formatter.html.twig.
40
 *
41
 * @param array $variables
42
 *   An associative array containing:
43 44 45
 *   - item: An ImageItem object.
 *   - item_attributes: An optional associative array of html attributes to be
 *     placed in the img tag.
46
 *   - image_style: An optional image style.
47
 *   - url: An optional \Drupal\Core\Url object.
48
 */
49
function template_preprocess_image_formatter(&$variables) {
50
  if ($variables['image_style']) {
51
    $variables['image'] = [
52 53
      '#theme' => 'image_style',
      '#style_name' => $variables['image_style'],
54
    ];
55 56
  }
  else {
57
    $variables['image'] = [
58
      '#theme' => 'image',
59
    ];
60
  }
61
  $variables['image']['#attributes'] = $variables['item_attributes'];
62

63
  $item = $variables['item'];
64

65
  // Do not output an empty 'title' attribute.
66
  if (mb_strlen($item->title) != 0) {
67
    $variables['image']['#title'] = $item->title;
68
  }
69

70
  if (($entity = $item->entity) && empty($item->uri)) {
71
    $variables['image']['#uri'] = $entity->getFileUri();
72 73
  }
  else {
74
    $variables['image']['#uri'] = $item->uri;
75 76
  }

77
  foreach (['width', 'height', 'alt'] as $key) {
78
    $variables['image']["#$key"] = $item->$key;
79
  }
80
}