From 683c40ffa54973d1176ac6e3d377aa840dacd58d Mon Sep 17 00:00:00 2001 From: Rosie Le Faive Date: Sat, 30 Mar 2024 06:55:16 -0300 Subject: [PATCH] Add Searchable Entity Formatter. --- .../SearchableEntityFormatter.php | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 src/Plugin/Field/FieldFormatter/SearchableEntityFormatter.php diff --git a/src/Plugin/Field/FieldFormatter/SearchableEntityFormatter.php b/src/Plugin/Field/FieldFormatter/SearchableEntityFormatter.php new file mode 100644 index 0000000..832dd81 --- /dev/null +++ b/src/Plugin/Field/FieldFormatter/SearchableEntityFormatter.php @@ -0,0 +1,100 @@ + 'search?f[0]', + 'search_var' => 'all_subjects', + 'search_term' => FALSE, + ] + parent::defaultSettings(); + } + + /** + * {@inheritdoc} + */ + public function settingsForm(array $form, FormStateInterface $form_state) { + $elements['search_link'] = [ + '#title' => t('Search base path'), + '#type' => 'textfield', + '#required' => TRUE, + '#default_value' => $this->getSetting('search_link'), + ]; + $elements['search_var'] = [ + '#title' => t('Search variable'), + '#type' => 'textfield', + '#required' => TRUE, + '#default_value' => $this->getSetting('search_var'), + ]; + $elements['search_term'] = [ + '#title' => t('Use label as search term'), + '#type' => 'checkbox', + '#default_value' => $this->getSetting('search_term'), + ]; + return $elements; + } + + /** + * {@inheritdoc} + */ + public function settingsSummary() { + $summary = []; + $summary[] = t('Search path: @search_link', ['@search_link' => $this->getSetting('search_link')]); + $summary[] = t('Variable: @search_var', ['@search_var' => $this->getSetting('search_var')]); + $summary[] = $this->getSetting('search_term') ? t('Use label as search term') : t('Use ID as search term'); + return $summary; + } + + /** + * {@inheritdoc} + */ + public function viewElements(FieldItemListInterface $items, $langcode) { + $par_elements = parent::viewElements($items, $langcode); + foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) { + $search_var = $this->getSetting('search_var'); + $search_term = $this->getSetting('search_term'); + + if ($search_term == TRUE) { + $param = $par_elements[$delta]['#title']; + } + else { + $param = $entity->id(); + } + + $url = \Drupal::service('facets.utility.url_generator')->getUrl([$search_var => [$param]]); + + $par_elements[$delta]['#url'] = $url; + + } + return $par_elements; + } + + /** + * {@inheritdoc} + */ + protected function checkAccess(EntityInterface $entity) { + return $entity->access('view label', NULL, TRUE); + } + +}