Skip to content

API Reference

Manual API reference for public classes and traits in the Image Link Formatter module.


ImageLinkFormatter

Plugin ID: image_link_formatter

Location: src/Plugin/Field/FieldFormatter/ImageLinkFormatter.php

Extends: \Drupal\image\Plugin\Field\FieldFormatter\ImageFormatter

A field formatter plugin that extends Drupal's core Image formatter to wrap images with a custom link field.

Overview

This formatter combines the standard image display capabilities of the core Image formatter with the ability to wrap the rendered image in a link provided by a custom link field on the same entity. The image and link are matched by field delta (position).

Methods

The plugin uses the ImageLinkFormatterTrait to provide these key methods:

  • create() — Factory method that injects the entity_field.manager service
  • settingsForm() — Adds custom link field options to the image formatter settings
  • settingsSummary() — Displays selected link field in the display configuration summary
  • viewElements() — Wraps rendered images in links based on field values

Usage

In your field display configuration:

  1. Select Image wrapped within link field as the formatter
  2. In settings, choose which link field provides the URL
  3. The image at delta 0 will wrap with link at delta 0, etc.

Example Configuration

// In display settings for an Image field:
'formatter' => [
  'type' => 'image_link_formatter',
  'settings' => [
    'image_style' => 'medium',
    'image_link' => 'field_link_url',  // Custom link field name
  ],
],

ResponsiveImageLinkFormatter

Plugin ID: responsive_image_link_formatter

Location: responsive_image_link_formatter/src/Plugin/Field/FieldFormatter/ResponsiveImageLinkFormatter.php

Extends: \Drupal\responsive_image\Plugin\Field\FieldFormatter\ResponsiveImageFormatter

A field formatter plugin that extends Drupal's core Responsive Image formatter to wrap responsive images with a custom link field.

Overview

Similar to ImageLinkFormatter, but for responsive images using art direction and breakpoint-based image styles. Uses the same ImageLinkFormatterTrait for link-wrapping logic.

Methods

See ImageLinkFormatterTrait for available methods.

Usage

Enable the responsive_image_link_formatter sub-module, then:

  1. Select Responsive image wrapped within link field as the formatter
  2. In settings, choose a responsive image style and the link field
  3. Works identically to standard formatter but with responsive images

Example Configuration

// In display settings for an Image field:
'formatter' => [
  'type' => 'responsive_image_link_formatter',
  'settings' => [
    'responsive_image_style' => 'hero_images',  // Responsive style with breakpoints
    'image_link' => 'field_link_url',
  ],
],

ImageLinkFormatterTrait

Location: src/Plugin/Field/FieldFormatter/ImageLinkFormatterTrait.php

Used by: ImageLinkFormatter, ResponsiveImageLinkFormatter

A trait that provides shared link-wrapping functionality for image formatters.

Overview

This trait encapsulates the logic for: - Injecting the entity_field.manager service - Discovering and listing available link fields - Extending formatter settings to include link field selection - Rendering images wrapped in links by delta matching

Protected Properties

These properties are available to subclasses that extend the formatters using this trait:

protected EntityFieldManagerInterface $entityFieldManager

The injected service for discovering field definitions and available fields on entities.

Injected by: create() method during plugin instantiation

Usage in subclasses:

// In your extending formatter class:
$fields = $this->entityFieldManager->getFieldDefinitions($entity_type, $bundle);

protected ?array $imageLinkFieldsOptions = null

Cached result of getLinkFieldsOptions() method, populated on first call to avoid repeated queries.

Type: array<string, string>|null — Null initially, populated with field names/labels after first access

Usage in subclasses:

// Check if options are already cached before calling getLinkFieldsOptions()
if ($this->imageLinkFieldsOptions === null) {
  $this->imageLinkFieldsOptions = $this->getLinkFieldsOptions();
}

Key Methods

create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static

Factory method that injects service dependencies.

Parameters: - $container — The service container - $configuration — Plugin configuration array containing field_definition, settings, label, view_mode, third_party_settings - $plugin_id — The plugin ID (e.g., 'image_link_formatter') - $plugin_definition — The plugin definition array

Returns: static — An instance of the formatter plugin with services injected

Example:

// This is called automatically during formatter instantiation
$formatter = ImageLinkFormatter::create($container, $config, 'image_link_formatter', $definition);

settingsForm(array $form, FormStateInterface $form_state): array

Extends the parent formatter's settings form to add custom link field options.

Parameters: - $form — The parent form array - $form_state — The form state object

Returns: array — The modified form with link field options added to image_link dropdown

What it does: 1. Calls parent's settingsForm() to get base image formatter settings 2. Queries entity for available custom link fields via getLinkFieldsOptions() 3. Adds discovered link fields to the 'image_link' select dropdown

Example:

// In field display UI, the 'Link image to' dropdown will show:
// - Standard core options (None, Content, Custom URL)
// - Custom link fields discovered by this method (field_url, field_external_link, etc.)

settingsSummary(): array

Provides a human-readable summary of formatter settings for the display management page.

Returns: array — Summary text describing selected image style and link field

Example output:

Image style: Medium
Link image to: field_link_url

viewElements(FieldItemListInterface $items, $langcode): array

Renders the image field with links wrapped around each image by delta.

Parameters: - $items — The field item list (containing image values) - $langcode — The language code for rendering

Returns: array — Render array with linked images

Key behavior: - Renders each image using parent formatter - Wraps each image with corresponding link field value by delta - Returns fully-rendered output with proper caching tags/contexts


getLinkFieldsOptions(): array

Discovers and returns available custom link fields for the current entity.

Returns: array — Associative array of link field names and labels - Key: field machine name (e.g., 'field_link_url') - Value: field label (e.g., 'Link URL')

Caching: Results are cached on first call in $imageLinkFieldsOptions to avoid repeated entity queries.

Example:

$options = $formatter->getLinkFieldsOptions();
// Returns:
// [
//   'field_custom_link' => 'Custom Link',
//   'field_product_url' => 'Product URL',
// ]

Service Dependencies

entity_field.manager

The EntityFieldManagerInterface service, injected during plugin instantiation via create().

Usage: Discovering field definitions and available link fields for the entity bundle being formatted.

$fields = $this->entityFieldManager->getFieldDefinitions($entity_type, $bundle);

Field Delta Matching

When both image and link fields have multiple values, matching is done by delta (position):

  • Image at delta 0 wraps with Link at delta 0
  • Image at delta 1 wraps with Link at delta 1
  • etc.

This allows flexible control: you can have different images linking to different URLs simply by maintaining parallel field values.

Example:

Image field values:        Link field values:
[0] => image1.jpg          [0] => /products/a
[1] => image2.jpg          [1] => /products/b
[2] => image3.jpg          [2] => /products/c

Result: Three images, each linking to a different product page.

Extending the Formatters

To extend either formatter with additional functionality:

namespace Drupal\my_module\Plugin\Field\FieldFormatter;

use Drupal\image_link_formatter\Plugin\Field\FieldFormatter\ImageLinkFormatter;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Custom image link formatter with tracking.
 */
class TrackingImageLinkFormatter extends ImageLinkFormatter {

  protected $analytics;

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->analytics = $container->get('my_module.analytics');
    return $instance;
  }

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = parent::viewElements($items, $langcode);
    // Modify elements to add tracking parameters
    foreach ($elements as &$element) {
      if (isset($element['#url'])) {
        $element['#url']->setOption('query', ['utm_source' => 'image']);
      }
    }
    return $elements;
  }
}