View source
<?php
namespace Drupal\image_popup\Plugin\Field\FieldFormatter;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\image\Entity\ImageStyle;
use Drupal\image\Plugin\Field\FieldFormatter\ImageFormatterBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ImagePopupFieldFormatter extends ImageFormatterBase implements ContainerFactoryPluginInterface {
protected $currentUser;
protected $linkGenerator;
protected $imageStyleStorage;
protected $configFactory;
protected $entityFieldManager;
protected $fieldOptions;
protected $parent;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, AccountInterface $current_user, LinkGeneratorInterface $link_generator, EntityStorageInterface $image_style_storage, ConfigFactoryInterface $config_factory, EntityFieldManagerInterface $entity_field_manager) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->currentUser = $current_user;
$this->linkGenerator = $link_generator;
$this->imageStyleStorage = $image_style_storage;
$this->configFactory = $config_factory;
$this->entityFieldManager = $entity_field_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], $container
->get('current_user'), $container
->get('link_generator'), $container
->get('entity_type.manager')
->getStorage('image_style'), $container
->get('config.factory'), $container
->get('entity_field.manager'));
}
public static function defaultSettings() {
$settings = [
'image_style' => '',
'image_style_popup' => '',
'image_link' => '',
] + parent::defaultSettings();
foreach ([
'image',
'image_popup',
] as $base) {
foreach ([
'title',
'alt',
] as $type) {
$settings["{$base}_{$type}_source"] = 'static';
$settings["{$base}_{$type}_static"] = '';
$settings["{$base}_{$type}_field"] = NULL;
}
}
return $settings;
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$image_styles = image_style_options(FALSE);
$elements = parent::settingsForm($form, $form_state);
$elements['image_heading'] = [
'#type' => 'html_tag',
'#tag' => 'h2',
'#value' => $this
->t('Image'),
];
$elements['image_style'] = [
'#title' => $this
->t('Image style'),
'#type' => 'select',
'#default_value' => $this
->getSetting('image_style'),
'#empty_option' => $this
->t('None (original image)'),
'#options' => $image_styles,
'#description' => [
'#markup' => $this->linkGenerator
->generate($this
->t('Configure Image Styles'), new Url('entity.image_style.collection')),
'#access' => $this->currentUser
->hasPermission('administer image styles'),
],
];
$elements = array_merge($elements, $this
->getAdditionalImageFields('image', $form_state));
$elements['image_popup_heading'] = [
'#type' => 'html_tag',
'#tag' => 'h2',
'#value' => $this
->t('Image Popup'),
];
$elements['image_style_popup'] = [
'#title' => $this
->t('Popup Image style'),
'#type' => 'select',
'#default_value' => $this
->getSetting('image_style_popup'),
'#empty_option' => $this
->t('None (original image)'),
'#options' => $image_styles,
'#description' => [
'#markup' => $this->linkGenerator
->generate($this
->t('Configure Image Styles'), new Url('entity.image_style.collection')),
'#access' => $this->currentUser
->hasPermission('administer image styles'),
],
];
$elements = array_merge($elements, $this
->getAdditionalImageFields('image_popup', $form_state));
return $elements;
}
public function settingsSummary() {
$summary = [];
$image_styles = image_style_options(FALSE);
unset($image_styles['']);
$image_style_setting = $this
->getSetting('image_style');
if (isset($image_styles[$image_style_setting])) {
$summary[] = $this
->t('Image style: @style', [
'@style' => $image_styles[$image_style_setting],
]);
}
else {
$summary[] = $this
->t('Original image');
}
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
if (!$items
->isEmpty()) {
$this->parent = $items[0]
->getEntity();
}
$files = $this
->getEntitiesToView($items, $langcode);
if (empty($files)) {
return [];
}
$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 = $this->configFactory
->get($config_name)
->getRawData();
$popup_width = 750;
if (!empty($image_style_popup_settings['effects'])) {
foreach ($image_style_popup_settings['effects'] as $effect) {
if ($effect['id'] == 'image_scale') {
$popup_width = $effect['data']['width'];
}
}
}
foreach ($files as $delta => $file) {
$image_uri = $file
->getFileUri();
$parameters = [
'fid' => $image_fid,
];
if ($image_style_popup) {
$parameters['image_style'] = $image_style_popup;
}
if ($image_style) {
$absolute_path = $this->imageStyleStorage
->load($image_style_name)
->buildUrl($image_uri);
}
else {
$absolute_path = Url::fromUri(file_create_url($image_uri))
->getUri();
}
$options = [
'query' => [
'alt' => $this
->getText('image_popup', 'alt'),
'title' => $this
->getText('image_popup', 'title'),
'modal-options' => Json::encode([
'width' => $popup_width,
]),
],
];
$link = [
'#type' => 'link',
'#title' => [
'#theme' => 'image',
'#alt' => $this
->getText('image', 'alt'),
'#title' => $this
->getText('image', 'title'),
'#uri' => $absolute_path,
],
'#attributes' => [
'class' => [
'use-ajax',
],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => $popup_width,
]),
],
'#url' => Url::fromRoute('image_popup.image_popup_render', $parameters, $options),
'#attached' => [
'library' => [
'core/drupal.dialog.ajax',
],
],
];
$elements[$delta] = $link;
}
return $elements;
}
protected function getText($base_field_id, $type) {
$source = $this
->getSetting("{$base_field_id}_{$type}_source");
if ($source === 'static') {
return $this
->getSetting("{$base_field_id}_{$type}_static");
}
elseif ($source === 'field') {
if (isset($this->parent)) {
$field = $this
->getSetting("{$base_field_id}_{$type}_field");
return $this->parent->{$field}->value;
}
}
return '';
}
protected function getFieldOptions(FormStateInterface $form_state) {
if (!isset($this->fieldOptions)) {
$this->fieldOptions = [];
$entity = $form_state
->getBuildInfo()['callback_object']
->getEntity();
$entity_type = $entity
->getTargetEntityTypeId();
$bundle = $entity
->getTargetBundle();
$field_map = $this->entityFieldManager
->getFieldMapByFieldType('string');
if (isset($field_map[$entity_type])) {
$field_ids = array_keys($field_map[$entity_type]);
$field_definitions = $this->entityFieldManager
->getFieldDefinitions($entity_type, $bundle);
foreach ($field_ids as $field_id) {
if (!empty($field_definitions[$field_id])) {
$this->fieldOptions[$field_id] = $field_definitions[$field_id]
->getLabel();
}
}
}
}
return $this->fieldOptions;
}
protected function getAdditionalImageFields($base_field_id, FormStateInterface $form_state) {
$fields = [];
foreach ([
'title' => $this
->t('Title'),
'alt' => $this
->t('alt'),
] as $id => $label) {
$fields["{$base_field_id}_{$id}_source"] = [
'#title' => $this
->t('@label source', [
'@label' => $label,
]),
'#type' => 'select',
'#default_value' => $this
->getSetting("{$base_field_id}_{$id}_source"),
'#options' => [
'static' => $this
->t('Fixed value'),
],
'#attributes' => [
'data-states-selector' => "{$base_field_id}_{$id}_source",
],
];
$fields["{$base_field_id}_{$id}_static"] = [
'#title' => $this
->t('@label text', [
'@label' => $label,
]),
'#type' => 'textfield',
'#default_value' => $this
->getSetting("{$base_field_id}_{$id}_static"),
'#states' => [
'visible' => [
":input[data-states-selector=\"{$base_field_id}_{$id}_source\"]" => [
'value' => 'static',
],
],
],
];
$field_options = $this
->getFieldOptions($form_state);
if ($field_options) {
$fields["{$base_field_id}_{$id}_source"]['#options']['field'] = $this
->t('Field value');
$fields["{$base_field_id}_{$id}_field"] = [
'#title' => $this
->t('@label text field', [
'@label' => $label,
]),
'#type' => 'select',
'#default_value' => $this
->getSetting("{$base_field_id}_{$id}_field"),
'#options' => $field_options,
'#states' => [
'visible' => [
":input[data-states-selector=\"{$base_field_id}_{$id}_source\"]" => [
'value' => 'field',
],
],
],
];
}
}
return $fields;
}
}