image_link_attributes-8.x-1.4/image_link_attributes.module

image_link_attributes.module
<?php

/**
 * @file
 * Contains image_link_attributes.module.
 */

use Drupal\Component\Utility\Unicode;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_help().
 */
function image_link_attributes_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the image_link_attributes module.
    case 'help.page.image_link_attributes':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Extends the default image field link formatter to add attributes for class=xxx, target=xxx, and rel=xxx.') . '</p>';
      return $output;

    default:
  }
}

/**
 * Implements hook_field_formatter_settings_summary_alter().
 */
function image_link_attributes_field_formatter_settings_summary_alter(&$summary, $context) {
  $available_attributes = \Drupal::config('image_link_attributes.config')->get('attributes') ?: [];
  $settings = $context['formatter']->getThirdPartySettings('image_link_attributes');
  $image_settings = $context['formatter']->getSettings();
  if (array_key_exists('image_link', $image_settings)) {
    $image_link = $image_settings['image_link'];
  }

  // Break when no linked field settings were found.
  if (!$settings) {
    return;
  }

  // Normalize the settings.
  $extended = $settings['extended'];
  $alternate_image = $settings['alternate_images'];

  $summary_items = [];

  // Insert Target into the summary_items array.
  if (!empty($settings['advanced']['target'])) {
    $summary_items[] = t('@label: <code>@attribute</code>', [
      '@label' => 'Target',
      '@attribute' => $settings['advanced']['target'],
    ]);
  }

  foreach ($available_attributes as $attribute => $info) {
    if (empty($settings['advanced'][$attribute]) || empty($image_link)) {
      continue;
    }

    // Provide default label / description for attributes.
    if (!$info['label']) {
      $info['label'] = str_replace('-', ' ', Unicode::ucfirst($attribute));
    }

    $summary_items[] = t('@label: <code>@attribute</code>', [
      '@label' => $info['label'],
      '@attribute' => $settings['advanced'][$attribute],
    ]);
  }

  if ($extended) {
    $list = [
      '#theme' => 'item_list',
      '#items' => $summary_items,
      '#title' => 'Link Attributes',
    ];

    $summary[] = $list;
  }

  if ($alternate_image) {
    $alternate_image_style = $settings['alternate_image_styles'];
    $image_list = [
      '#theme' => 'item_list',
      '#items' => ['Image Style' => $alternate_image_style],
      '#title' => 'Linked Image Style',
    ];

    $summary[] = $image_list;
  }
}

/**
 * Implements hook_field_formatter_third_party_settings_form().
 */
function image_link_attributes_field_formatter_third_party_settings_form($plugin, $field_definition, $view_mode, $form, $form_state) {

  if ($plugin->getPluginId() == 'image' || $plugin->getPluginId() == 'responsive_image') {

    $target_options = \Drupal::config('image_link_attributes.config')->get('targets') ?: [];
    $available_attributes = \Drupal::config('image_link_attributes.config')->get('attributes') ?: [];
    $settings = $plugin->getThirdPartySettings('image_link_attributes');

    if (!array_key_exists('extended', $settings)) {
      $settings['extended'] = 0;
    }

    $element['extended'] = [
      '#title' => t('Add custom attribute(s) to the link?'),
      '#type' => 'checkbox',
      '#default_value' => $settings['extended'],
      '#states' => [
        'invisible' => [
          'select[name$="[settings][image_link]"]' => ['value' => ''],
        ],
      ],
    ];

    $element['advanced'] = [
      '#title' => t('Advanced'),
      '#type' => 'details',
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#states' => [
        'invisible' => [
          ['select[name$="[settings][image_link]"]' => ['value' => '']],
          ['input[name$="[third_party_settings][image_link_attributes][extended]"]' => ['unchecked' => TRUE]],
        ],
      ],
    ];

    $element['advanced']['target'] = [
      '#type' => 'select',
      '#title' => 'Target',
      '#description' => t('Select the value for the <code>@attribute</code> attribute.', ['@attribute' => 'target']),
      '#default_value' => $settings['advanced']['target'] ?? '',
    ];

    $element['advanced']['target']['#options'][''] = t('none');
    foreach ($target_options as $target => $option) {
      $element['advanced']['target']['#options'][$target] = $option['label'];
    }

    foreach ($available_attributes as $attribute => $info) {
      // Provide default label / description for attributes.
      if (!$info['label']) {
        $info['label'] = str_replace('-', ' ', Unicode::ucfirst($attribute));
      }
      if (!$info['description']) {
        $info['description'] = t('Enter value for <code>@attribute</code> attribute.', ['@attribute' => $attribute]);
      }

      $element['advanced'][$attribute] = [
        '#type' => 'textfield',
        '#title' => $info['label'],
        '#description' => $info['description'],
        '#default_value' => $settings['advanced'][$attribute] ?? '',
      ];
    }

    // Settings for alternate images.
    if (!array_key_exists('alternate_images', $settings)) {
      $settings['alternate_images'] = 0;
    }

    // Checkbox for alternate images.
    $element['alternate_images'] = [
      '#title' => t('Link to alternate Image Style?'),
      '#type' => 'checkbox',
      '#default_value' => $settings['alternate_images'],
      '#states' => [
        'invisible' => [
          [
            'select[name$="[settings][image_link]"]' => [
              ['value' => ''],
              ['value' => 'content'],
            ],
          ],
        ],
      ],
    ];

    // Settings for Alternate Image Styles.
    if (!array_key_exists('alternate_image_styles', $settings)) {
      $settings['alternate_image_styles'] = 0;
    }

    // Options for Alternate Image Styles.
    $element['alternate_image_styles'] = [
      '#type' => 'select',
      '#title' => t('Alternate Image Styles'),
      '#default_value' => $settings['alternate_image_styles'],
      '#options' => image_style_options(FALSE),
      '#states' => [
        'invisible' => [
          [
            'select[name$="[settings][image_link]"]' => [
                ['value' => ''],
                ['value' => 'content'],
            ],
          ],
          ['input[name$="[third_party_settings][image_link_attributes][alternate_images]"]' => ['unchecked' => TRUE]],
        ],
      ],
    ];

    return $element;
  }
}

/**
 * Implements hook_preprocess_field().
 */
function image_link_attributes_preprocess_field(array &$variables) {
  $element =& $variables['element'];

  if ($element['#formatter'] == 'image' || $element['#formatter'] == 'responsive_image') {
    $items =& $variables['items'];

    $entity = $element['#object'];
    $view_mode  = $element['#view_mode'];
    $field_name = $element['#field_name'];

    $entity_display =
      EntityViewDisplay::collectRenderDisplay($entity, $view_mode);

    $field_display = $entity_display->getComponent($field_name);

    $custom_settings =
      $field_display['third_party_settings']['image_link_attributes'] ?? [];

    $is_enabled = $custom_settings['extended'] ?? FALSE;

    // If there is an alternate image style, get it, assign path.
    $alternate_image = $custom_settings['alternate_images'] ?? FALSE;

    if ($alternate_image) {
      $alternate_image_style = $custom_settings['alternate_image_styles'];
      $style = ImageStyle::load($alternate_image_style);
      foreach (Element::children($items) as $child_name) {
        $delta =& $items[$child_name];
        $content =& $delta['content'];
        $alternate_path = $content['#alternate_path'] ?? "";
        $image_id = $items[$child_name]['content']['#item']->getValue()['target_id'];
        if (!empty($image_id)) {
          $image_file = File::load($image_id);
          $alternate_path = $style->buildUrl($image_file->uri->value);
          $content['#alternate_path'] = $alternate_path;
        }
      }
    }

    // If there are advanced attributes, get them and assign them.
    if ($is_enabled) {
      $advanced_attributes = array_filter($custom_settings['advanced']);
      foreach (Element::children($items) as $child_name) {
        $delta =& $items[$child_name];
        $content =& $delta['content'];
        $link_attributes = $content['#link_attributes'] ?? [];
        $link_attributes = array_merge($link_attributes, $advanced_attributes);
        $content['#link_attributes'] = $link_attributes;
      }
    }
  }
}

/**
 * Implements hook_theme_registry_alter().
 */
function image_link_attributes_theme_registry_alter(array &$theme_registry) {
  $module_path = \Drupal::service('extension.list.module')->getPath('image_link_attributes');
  $theme_registry['image_formatter']['path'] = $module_path . '/templates/field';
  $theme_registry['responsive_image_formatter']['path'] = $module_path . '/templates/field';
}

/**
 * Implements hook_theme().
 */
function image_link_attributes_theme($existing, $type, $theme, $path) {
  return [
    'image_formatter' => [
      'variables' => [
        'item' => NULL,
        'item_attributes' => NULL,
        'link_attributes' => [],
        'url' => NULL,
        'image_style' => NULL,
        'alternate_path' => NULL,
      ],
    ],
    'responsive_image_formatter' => [
      'variables' => [
        'item' => NULL,
        'item_attributes' => NULL,
        'link_attributes' => [],
        'url' => NULL,
        'image_style' => NULL,
        'alternate_path' => NULL,
      ],
    ],
  ];
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc