From 67e4be9881bb974bcf41b21cb8ba804442ad5573 Mon Sep 17 00:00:00 2001 From: Jonathan Hunt Date: Thu, 29 Apr 2021 12:04:37 +1200 Subject: [PATCH] Add formatter setting to suppress MARC Relator code in () --- .../FieldFormatter/TypedRelationFormatter.php | 41 ++++++++++++++++++- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/src/Plugin/Field/FieldFormatter/TypedRelationFormatter.php b/src/Plugin/Field/FieldFormatter/TypedRelationFormatter.php index 2ebce91..c2e597e 100644 --- a/src/Plugin/Field/FieldFormatter/TypedRelationFormatter.php +++ b/src/Plugin/Field/FieldFormatter/TypedRelationFormatter.php @@ -4,6 +4,7 @@ use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter; use Drupal\Core\Field\FieldItemListInterface; +use Drupal\Core\Form\FormStateInterface; /** * Plugin implementation of the 'TypedRelationFormatter'. @@ -18,6 +19,38 @@ */ class TypedRelationFormatter extends EntityReferenceLabelFormatter { + /** + * {@inheritdoc} + */ + public static function defaultSettings() { + return [ + 'suppress_code' => FALSE, + ] + parent::defaultSettings(); + } + /** + * {@inheritdoc} + */ + public function settingsForm(array $form, FormStateInterface $form_state) { + + $elements = parent::settingsForm($form, $form_state); + $elements['suppress_code'] = [ + '#title' => t('Hide code in () after label, if present'), + '#type' => 'checkbox', + '#default_value' => $this->getSetting('suppress_code'), + ]; + + return $elements; + } + + /** + * {@inheritdoc} + */ + public function settingsSummary() { + $summary = parent::settingsSummary(); + $summary[] = $this->getSetting('suppress_code') ? t('Suppress code in (), if present') : t('Show code in (), if present'); + return $summary; + } + /** * {@inheritdoc} */ @@ -28,9 +61,13 @@ public function viewElements(FieldItemListInterface $items, $langcode) { $rel_types = $item->getRelTypes(); $rel_type = isset($rel_types[$item->rel_type]) ? $rel_types[$item->rel_type] : $item->rel_type; - if (!empty($rel_type)) { - $elements[$delta]['#prefix'] = $rel_type . ': '; + + // Suppress code, e.g. change Author (aut) to Author. + if ($this->getSetting('suppress_code') == TRUE) { + $rel_type = preg_replace('/ \([^()]*\)/', '', $rel_type); } + + $elements[$delta]['#prefix'] = $rel_type . ': '; } return $elements;