logo

Extra Block Types (EBT) - Nieuwe Layout Builder ervaring❗

Extra Block Types (EBT) - gestileerde, aanpasbare bloktypes: Slideshows, Tabs, Cards, Accordions en vele andere. Ingebouwde instellingen voor achtergrond, DOM Box, javascript-plugins. Ervaar vandaag al de toekomst van layout building.

Demo EBT-modules Download EBT-modules

❗Extra Paragraph Types (EPT) - Nieuwe Paragraphs ervaring

Extra Paragraph Types (EPT) - analoge op paragrafen gebaseerde set modules.

Demo EPT-modules Download EPT-modules

Scroll
04/10/2025, by Ivan

Menu

Een field formatter module formatteert veldgegevens voor weergave aan de eindgebruiker. Field formatters worden gedefinieerd als plugins, dus het is aan te raden eerst kennis te maken met de Plugin API voordat u een nieuwe field formatter schrijft.

De field formatter klasse

Bestand: /modules/random/src/Plugin/Field/FieldFormatter/RandomDefaultFormatter.php

<?php

namespace Drupal\random\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;

/**
 * Plugin implementation of the 'Random_default' formatter.
 *
 * @FieldFormatter(
 *   id = "Random_default",
 *   label = @Translation("Random text"),
 *   field_types = {
 *     "Random"
 *   }
 * )
 */
class RandomDefaultFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = [];
    $summary[] = $this->t('Displays the random string.');
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta => $item) {
      // Render each element as markup.
      $element[$delta] = ['#markup' => $item->value];
    }

    return $element;
  }

}

Formatter instellingen

Als uw formatter aangepaste instellingen voor de weergave nodig heeft, zijn er drie stappen:

  • Overschrijf PluginSettingsBase::defaultSettings() om standaardwaarden in te stellen
  • Maak een configuratieschema voor de door u gedefinieerde instellingen
  • Maak een formulier zodat gebruikers de instellingen kunnen wijzigen

Stap 1: Overschrijf PluginSettingsBase::defaultSettings()

public static function defaultSettings() {
  return [
    'text_length' => 'short',
  ] + parent::defaultSettings();
}

Stap 2: Maak een schema voor de configuratie

[MODULE ROOT]/config/schema/[MODULE_NAME].schema.yml
field.formatter.settings.[FORMATTER ID]:
  type: mapping
  label: 'FORMATTER NAME text length'
  mapping:
    text_length:
      type: string
      label: 'Text Length'

Stap 3: Maak een formulier om de instellingen te wijzigen

use Drupal\Core\Form\FormStateInterface;
public function settingsForm(array $form, FormStateInterface $form_state) {
  $form['text_length'] = [
    '#title' => $this->t('Text length'),
    '#type' => 'select',
    '#options' => [
      'short' => $this->t('Short'),
      'long' => $this->t('Long'),
    ],
    '#default_value' => $this->getSetting('text_length'),
  ];

  return $form;
}

Gebruik van #ajax in instellingenformulieren

Het gebruik van #ajax in instellingenformulieren is niet eenvoudig omdat het fragment dat in settingsForm() wordt gemaakt diep genest is. In dit voorbeeld tonen we een extra veld enkel als een andere waarde geselecteerd wordt.

$form['display_type'] = [
  '#title' => $this->t('Display Type'),
  '#type' => 'select',
  '#options' => [
    'label' => $this->t('Label'),
    'entity' => $this->t('Entity'),
  ],
  '#default_value' => $this->getSetting('display_type'),
  '#ajax' => [
    'wrapper' => 'private_message_thread_member_formatter_settings_wrapper',
    'callback' => [$this, 'ajaxCallback'],
  ],
];

Daarna de callback:

public function ajaxCallback(array $form, FormStateInterface $form_state) {
  $field_name = $this->fieldDefinition->getItemDefinition()->getFieldDefinition()->getName();
  $element_to_return = 'entity_display_mode';

  return $form['fields'][$field_name]['plugin']['settings_edit_form']['settings'][$element_to_return];
}

Dependency Injection in field formatters

Om Dependency Injection te gebruiken in field formatters:

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;

class MyFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
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('entity.manager')
  );
}
protected $entityManager;

public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityManagerInterface $entityManager) {
  parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);

  $this->entityManager = $entityManager;
}

Nu kunt u $this->entityManager overal in uw formatter klasse gebruiken.