image.field.inc 2.21 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\Component\Utility\NestedArray;
9
use Drupal\Component\Utility\Unicode;
10
use Drupal\Core\Render\Element;
11

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

24
  $variables['attributes'] = array('class' => array('image-widget', 'form-managed-file', 'clearfix'));
25

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

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

36 37 38
}

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

65
  $item = $variables['item'];
66

67
  // Do not output an empty 'title' attribute.
68
  if (Unicode::strlen($item->title) != 0) {
69
    $variables['image']['#title'] = $item->title;
70
  }
71

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

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