You are here

public function ImagePopupFieldFormatter::viewElements in Simple Image Popup 8

Same name and namespace in other branches
  1. 2.x src/Plugin/Field/FieldFormatter/ImagePopupFieldFormatter.php \Drupal\image_popup\Plugin\Field\FieldFormatter\ImagePopupFieldFormatter::viewElements()

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 FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/ImagePopupFieldFormatter.php, line 176
Contains \Drupal\image_popup\Plugin\Field\FieldFormatter\ImagePopupFieldFormatter.

Class

ImagePopupFieldFormatter
Plugin implementation of the 'image_popup_field_formatter' formatter.

Namespace

Drupal\image_popup\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = array();
  $files = $this
    ->getEntitiesToView($items, $langcode);
  $image_style_popup = $this
    ->getSetting('image_style_popup');
  $image_style_name = $this
    ->getSetting('image_style');
  $image_fid = $files[0]
    ->get('fid')
    ->getValue()[0]['value'];
  $image_style = ImageStyle::load($image_style_name);
  $config_name = "image.style." . $image_style_popup;
  $image_style_popup_settings = \Drupal::config($config_name)
    ->getRawData();

  //$image_style_popup_settings = entity_load('image_style', $image_style_popup);
  $popup_width = 750;
  foreach ($image_style_popup_settings['effects'] as $key => $effect) {
    if ($effect['id'] == 'image_scale') {
      $popup_width = $effect['data']['width'];
    }
  }
  foreach ($files as $delta => $file) {
    $image_uri = $file
      ->getFileUri();
    if ($image_style) {
      $absolute_path = $this->imageStyleStorage
        ->load($image_style_name)
        ->buildUrl($image_uri);
    }
    else {

      // Get absolute path for original image.
      $absolute_path = Url::fromUri(file_create_url($image_uri))
        ->getUri();
    }
    global $base_url;
    $img = "<img src='" . $absolute_path . "'><img>";
    $img_link = "<a href='" . $base_url . "/image_popup/render/" . $image_fid . "/" . $image_style_popup . "' class='use-ajax' data-dialog-type='modal' data-dialog-options='{\"width\":" . $popup_width . "}'>" . $img . "</a>";
    $elements[$delta] = array(
      '#markup' => $img_link,
    );
  }
  return $elements;
}