Skip to main content
Drupal 10: creating a field formatter: the case of an Image Grid

The field formatter lets you define the way in which data can be rendered. This feature is very useful for developing renderings that can be used on multiple sites.

To make things easier to understand, we're going to create a formatter to display images as grids.
( NB: We won't dwell on styles in this tutorial. )

Prerequisite:
Creating custom field types, widgets, and formatters

Where to start?
You need to define the field responsible for data management, in our case the image field.

namespace Drupal\image\Plugin\Field\FieldType;


....
 *   default_widget = "image_image",
 *   default_formatter = "image",
...

# voir le fichier core/modules/image/src/Plugin/Field/FieldType/ImageItem.php

from this, we determine the default format: image. We'll extend it to create our own.

<?php

namespace Drupal\more_fields\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\image\Plugin\Field\FieldFormatter\ImageFormatter;

/**
 * Plugin implementation of the 'FieldGalleries' formatter.
 *
 * @FieldFormatter(
 *   id = "more_field_mit_gallery_formatter",
 *   label = @Translation("Mitor Gallery (Grid)"),
 *   field_types = {
 *     "image"
 *   },
 *   quickedit = {
 *     "editor" = "image"
 *   }
 * )
 */
class FieldMitorGalleryFormatter extends ImageFormatter {


}

This minimal code already displays our field in the formatter's configuration options.

We now add a method to manage the display of our fields.

  /**
   *
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [
      '#theme' => 'more_field_mit_gallery_formatter',
      'items' => parent::viewElements($items, $langcode)
    ];
    return $elements;
  }

For ease of rendering, we've opted to use a theme (but you're free to use another approach).
We'll come back to this later.

Next, we've added 2 methods, defaultSettings and settingsForm, to manage configuration.

  /**
   *
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      "container_class" => "",
      "item_class" => ""
    ] + parent::defaultSettings();
  }


  /**
   *
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $elements = parent::settingsForm($form, $form_state);
    $elements['container_class'] = [
      "#type" => "text_field",
      "#title" => $this->t('Container class'),
      '#default_value' => $this->getSetting('container_class')
    ];
    $elements['item_class'] = [
      "#type" => "text_field",
      "#title" => $this->t('Item class'),
      '#default_value' => $this->getSetting('item_class')
    ];
    return $elements;
  }
Profile picture for user admin Stephane K

Écrit le

Il y'a 1 year
Modifié
Il y'a 2 weeks
Loading ...
WhatsApp
Support Habeuk : +237 694 900 622
WhatsApp Send