class ImagePopupFieldFormatter in Simple Image Popup 2.x
Same name and namespace in other branches
- 8 src/Plugin/Field/FieldFormatter/ImagePopupFieldFormatter.php \Drupal\image_popup\Plugin\Field\FieldFormatter\ImagePopupFieldFormatter
Plugin implementation of the 'image_popup_field_formatter' formatter.
Plugin annotation
@FieldFormatter(
id = "image_popup_field_formatter",
label = @Translation("Image Popup"),
field_types = {
"image"
}
)
Hierarchy
- class \Drupal\Component\Plugin\PluginBase implements DerivativeInspectionInterface, PluginInspectionInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
- class \Drupal\Core\Field\PluginSettingsBase implements DependentPluginInterface, PluginSettingsInterface
- class \Drupal\Core\Field\FormatterBase implements FormatterInterface, ContainerFactoryPluginInterface
- class \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase
- class \Drupal\file\Plugin\Field\FieldFormatter\FileFormatterBase
- class \Drupal\image\Plugin\Field\FieldFormatter\ImageFormatterBase
- class \Drupal\image_popup\Plugin\Field\FieldFormatter\ImagePopupFieldFormatter implements ContainerFactoryPluginInterface
- class \Drupal\image\Plugin\Field\FieldFormatter\ImageFormatterBase
- class \Drupal\file\Plugin\Field\FieldFormatter\FileFormatterBase
- class \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase
- class \Drupal\Core\Field\FormatterBase implements FormatterInterface, ContainerFactoryPluginInterface
- class \Drupal\Core\Field\PluginSettingsBase implements DependentPluginInterface, PluginSettingsInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
Expanded class hierarchy of ImagePopupFieldFormatter
File
- src/
Plugin/ Field/ FieldFormatter/ ImagePopupFieldFormatter.php, line 31
Namespace
Drupal\image_popup\Plugin\Field\FieldFormatterView source
class ImagePopupFieldFormatter extends ImageFormatterBase implements ContainerFactoryPluginInterface {
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The link generator.
*
* @var \Drupal\Core\Utility\LinkGeneratorInterface
*/
protected $linkGenerator;
/**
* The image style entity storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $imageStyleStorage;
/**
* Config factory service.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The Entity Field Manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* An array of valid fields to use for alt or title text.
*
* @var array
*/
protected $fieldOptions;
/**
* The field's parent.
*
* @var \Drupal\Core\Entity\EntityInterface
*/
protected $parent;
/**
* Constructs an ImageFormatter object.
*
* @param string $plugin_id
* The plugin_id for the formatter.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The definition of the field to which the formatter is associated.
* @param array $settings
* The formatter settings.
* @param string $label
* The formatter label display setting.
* @param string $view_mode
* The view mode.
* @param array $third_party_settings
* Any third party settings settings.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
* @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
* The link generator service.
* @param \Drupal\Core\Entity\EntityStorageInterface $image_style_storage
* The entity storage for the image.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
*/
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;
}
/**
* {@inheritdoc}
*/
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'));
}
/**
* {@inheritdoc}
*/
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;
}
/**
* {@inheritdoc}
*/
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;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$image_styles = image_style_options(FALSE);
// Unset possible 'No defined styles' option.
unset($image_styles['']);
// Styles could be lost because of enabled/disabled modules that defines
// their styles in code.
$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;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
// Set this->parent so that alt and title text from can be taken from the
// parent entity later on.
if (!$items
->isEmpty()) {
$this->parent = $items[0]
->getEntity();
}
$files = $this
->getEntitiesToView($items, $langcode);
// If there are no files, return an empty element.
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 {
// Get absolute path for original image.
$absolute_path = Url::fromUri(file_create_url($image_uri))
->getUri();
}
// Create a url query to tell the controller how to build the modal.
$options = [
'query' => [
'alt' => $this
->getText('image_popup', 'alt'),
'title' => $this
->getText('image_popup', 'title'),
'modal-options' => Json::encode([
'width' => $popup_width,
]),
],
];
// Create the link.
$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;
}
/**
* Gets the text needed for alt and title text based on configuration.
*
* This will only behave properly if $this->parent is set to the parent
* entity of this field.
*
* @return string
* The text.
*/
protected function getText($base_field_id, $type) {
$source = $this
->getSetting("{$base_field_id}_{$type}_source");
if ($source === 'static') {
// If the source is static, get the static value.
return $this
->getSetting("{$base_field_id}_{$type}_static");
}
elseif ($source === 'field') {
// If the source is a field, get that field's value from the parent.
if (isset($this->parent)) {
$field = $this
->getSetting("{$base_field_id}_{$type}_field");
return $this->parent->{$field}->value;
}
}
return '';
}
/**
* Find fields on the entity that are valid alt or title text.
*
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return array
* The valid fields as $id => $title.
*/
protected function getFieldOptions(FormStateInterface $form_state) {
// The result is kept in $this->fieldOptions so that it only needs to be
// processed once per instantiation of this class.
if (!isset($this->fieldOptions)) {
$this->fieldOptions = [];
// Discover the entity type and bundle this field is being created for.
$entity = $form_state
->getBuildInfo()['callback_object']
->getEntity();
$entity_type = $entity
->getTargetEntityTypeId();
$bundle = $entity
->getTargetBundle();
// Get all the string fields.
$field_map = $this->entityFieldManager
->getFieldMapByFieldType('string');
// Find fields from the map that are on this entity type and bundle.
if (isset($field_map[$entity_type])) {
$field_ids = array_keys($field_map[$entity_type]);
$field_definitions = $this->entityFieldManager
->getFieldDefinitions($entity_type, $bundle);
// Provide the entity's string fields as options.
foreach ($field_ids as $field_id) {
if (!empty($field_definitions[$field_id])) {
$this->fieldOptions[$field_id] = $field_definitions[$field_id]
->getLabel();
}
}
}
}
return $this->fieldOptions;
}
/**
* Creates alt and title fields for a base image context field.
*
* @param string $base_field_id
* The field to create more fields for.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return array
* The fields.
*/
protected function getAdditionalImageFields($base_field_id, FormStateInterface $form_state) {
$fields = [];
// Create fields for alt and title text.
foreach ([
'title' => $this
->t('Title'),
'alt' => $this
->t('alt'),
] as $id => $label) {
// Create a field to select the method for adding alt or title text.
$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",
],
];
// Create a field for a static text value.
$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',
],
],
],
];
// Check to see if there are other fields that can be used as alt or title
// fields.
$field_options = $this
->getFieldOptions($form_state);
if ($field_options) {
// Add the option to use a field value for the text.
$fields["{$base_field_id}_{$id}_source"]['#options']['field'] = $this
->t('Field value');
// Create a field for selecting a different field on the entity.
$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;
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
public | function | 2 | |
DependencySerializationTrait:: |
public | function | 2 | |
EntityReferenceFormatterBase:: |
public | function |
Loads the entities referenced in that field across all the entities being
viewed. Overrides FormatterBase:: |
|
EntityReferenceFormatterBase:: |
public | function |
Overrides FormatterBase:: |
|
FileFormatterBase:: |
protected | function |
Checks access to the given entity. Overrides EntityReferenceFormatterBase:: |
|
FileFormatterBase:: |
protected | function |
Returns whether the entity referenced by an item needs to be loaded. Overrides EntityReferenceFormatterBase:: |
1 |
FormatterBase:: |
protected | property | The field definition. | |
FormatterBase:: |
protected | property | The label display setting. | |
FormatterBase:: |
protected | property |
The formatter settings. Overrides PluginSettingsBase:: |
|
FormatterBase:: |
protected | property | The view mode. | |
FormatterBase:: |
protected | function | Returns the value of a field setting. | |
FormatterBase:: |
protected | function | Returns the array of field settings. | |
FormatterBase:: |
public static | function |
Returns if the formatter can be used for the provided field. Overrides FormatterInterface:: |
14 |
ImageFormatterBase:: |
protected | function |
Returns the referenced entities for display. Overrides EntityReferenceFormatterBase:: |
|
ImagePopupFieldFormatter:: |
protected | property | Config factory service. | |
ImagePopupFieldFormatter:: |
protected | property | The current user. | |
ImagePopupFieldFormatter:: |
protected | property | The Entity Field Manager. | |
ImagePopupFieldFormatter:: |
protected | property | An array of valid fields to use for alt or title text. | |
ImagePopupFieldFormatter:: |
protected | property | The image style entity storage. | |
ImagePopupFieldFormatter:: |
protected | property | The link generator. | |
ImagePopupFieldFormatter:: |
protected | property | The field's parent. | |
ImagePopupFieldFormatter:: |
public static | function |
Creates an instance of the plugin. Overrides FormatterBase:: |
|
ImagePopupFieldFormatter:: |
public static | function |
Defines the default settings for this plugin. Overrides PluginSettingsBase:: |
|
ImagePopupFieldFormatter:: |
protected | function | Creates alt and title fields for a base image context field. | |
ImagePopupFieldFormatter:: |
protected | function | Find fields on the entity that are valid alt or title text. | |
ImagePopupFieldFormatter:: |
protected | function | Gets the text needed for alt and title text based on configuration. | |
ImagePopupFieldFormatter:: |
public | function |
Returns a form to configure settings for the formatter. Overrides FormatterBase:: |
|
ImagePopupFieldFormatter:: |
public | function |
Returns a short summary for the current formatter settings. Overrides FormatterBase:: |
|
ImagePopupFieldFormatter:: |
public | function |
Builds a renderable array for a field value. Overrides FormatterInterface:: |
|
ImagePopupFieldFormatter:: |
public | function |
Constructs an ImageFormatter object. Overrides FormatterBase:: |
|
MessengerTrait:: |
protected | property | The messenger. | 27 |
MessengerTrait:: |
public | function | Gets the messenger. | 27 |
MessengerTrait:: |
public | function | Sets the messenger. | |
PluginBase:: |
protected | property | Configuration information passed into the plugin. | 1 |
PluginBase:: |
protected | property | The plugin implementation definition. | 1 |
PluginBase:: |
protected | property | The plugin_id. | |
PluginBase:: |
constant | A string which is used to separate base plugin IDs from the derivative ID. | ||
PluginBase:: |
public | function |
Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the definition of the plugin implementation. Overrides PluginInspectionInterface:: |
2 |
PluginBase:: |
public | function |
Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface:: |
|
PluginBase:: |
public | function | Determines if the plugin is configurable. | |
PluginSettingsBase:: |
protected | property | Whether default settings have been merged into the current $settings. | |
PluginSettingsBase:: |
protected | property | The plugin settings injected by third party modules. | |
PluginSettingsBase:: |
public | function |
Calculates dependencies for the configured plugin. Overrides DependentPluginInterface:: |
6 |
PluginSettingsBase:: |
public | function |
Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
protected | function | Merges default settings values into $settings. | |
PluginSettingsBase:: |
public | function |
Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface:: |
3 |
PluginSettingsBase:: |
public | function |
Sets the value of a setting for the plugin. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Sets the settings for the plugin. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Unsets a third-party setting. Overrides ThirdPartySettingsInterface:: |
|
StringTranslationTrait:: |
protected | property | The string translation service. | 4 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. |