KeyValueFormatter.php in Key value field 8
File
src/Plugin/Field/FieldFormatter/KeyValueFormatter.php
View source
<?php
namespace Drupal\key_value_field\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\text\Plugin\Field\FieldFormatter\TextDefaultFormatter;
use Drupal\Core\Form\FormStateInterface;
class KeyValueFormatter extends TextDefaultFormatter {
public static function defaultSettings() {
$settings = parent::defaultSettings();
$settings['value_only'] = FALSE;
return $settings;
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);
$form['value_only'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Value only'),
'#default_value' => $this
->getSetting('value_only'),
'#description' => $this
->t('Make the formatter hide the "Key" part of the field and display the "Value" only.'),
'#weight' => 4,
];
return $form;
}
public function settingsSummary() {
$summary = parent::settingsSummary();
$key = $this
->getSetting('value_only') ? '' : ' [Key] : ';
$summary[] = t('Display format: @key [Value].', [
'@key' => $key,
]);
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$value_elements = parent::viewElements($items, $langcode);
$elements = [];
foreach ($items as $delta => $item) {
if (!$this
->getSetting('value_only')) {
$elements[$delta]['key'] = [
'#plain_text' => nl2br($item->key . ' : '),
];
}
$elements[$delta]['value'] = $value_elements[$delta];
}
return $elements;
}
}