You are here

public function BackgroundImageFormatter::viewElements in Simple Background image formatter 8

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides ImageFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/BackgroundImageFormatter.php, line 107

Class

BackgroundImageFormatter
Plugin implementation of the background_image_formatter.

Namespace

Drupal\background_image_formatter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $image_style = NULL;
  if (!$this
    ->isBackgroundImageDisplay()) {
    return $elements;
  }
  $image_style = $this
    ->getSetting('image_style');
  if (!empty($image_style)) {
    $image_style = ImageStyle::load($image_style);
  }
  $files = $this
    ->getEntitiesToView($items, $langcode);
  foreach ($files as $delta => $entity) {
    if ($files instanceof EntityInterface) {
      continue;
    }
    $image_url = file_url_transform_relative(file_create_url($entity
      ->getFileUri()));
    $id = $entity
      ->id();
    if ($image_style) {
      $image_uri = $entity
        ->getFileUri();
      $image_url = ImageStyle::load($image_style
        ->getName())
        ->buildUrl($image_uri);
    }
    $selector = strip_tags($this
      ->getSetting('background_image_selector'));

    // Only add an id when using inline styles.
    if ($this
      ->getSetting('background_image_output_type') === 'inline') {
      $selector .= '_' . $id;
    }
    $theme = [
      '#background_image_selector' => $selector,
      '#image_uri' => $image_url,
    ];
    array_push($elements, $this
      ->renderElements($delta, $theme, $id));
  }
  return $elements;
}