TestFieldPrepareViewFormatter.php in Drupal 10
File
core/modules/field/tests/modules/field_test/src/Plugin/Field/FieldFormatter/TestFieldPrepareViewFormatter.php
View source
<?php
namespace Drupal\field_test\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
class TestFieldPrepareViewFormatter extends FormatterBase {
public static function defaultSettings() {
return [
'test_formatter_setting_additional' => 'dummy test string',
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_formatter_setting_additional'] = [
'#title' => t('Setting'),
'#type' => 'textfield',
'#size' => 20,
'#default_value' => $this
->getSetting('test_formatter_setting_additional'),
'#required' => TRUE,
];
return $element;
}
public function settingsSummary() {
$summary = [];
$summary[] = t('@setting: @value', [
'@setting' => 'test_formatter_setting_additional',
'@value' => $this
->getSetting('test_formatter_setting_additional'),
]);
return $summary;
}
public function prepareView(array $entities_items) {
foreach ($entities_items as $items) {
foreach ($items as $item) {
if (!$item
->isEmpty()) {
$item->additional_formatter_value = $item->value + 1;
}
}
}
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = [
'#markup' => $this
->getSetting('test_formatter_setting_additional') . '|' . $item->value . '|' . $item->additional_formatter_value,
];
}
return $elements;
}
}