SamplesDefaultFormatter.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace Drupal\materio_samples\Plugin\Field\FieldFormatter;
  3. use Drupal\Core\Field\FormatterBase;
  4. use Drupal\Core\Field\FieldItemListInterface;
  5. use Drupal\taxonomy\Entity\Term;
  6. /**
  7. * Plugin implementation of the 'materio_samples_default_formatter' formatter.
  8. *
  9. * @FieldFormatter(
  10. * id = "materio_samples_default_formatter",
  11. * module = "materio_samples",
  12. * label = @Translation("Simple list key paired formatter"),
  13. * field_types = {
  14. * "materio_samples_field"
  15. * }
  16. * )
  17. */
  18. class SamplesDefaultFormatter extends FormatterBase {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public function viewElements(FieldItemListInterface $items, $langcode) {
  23. $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  24. $elements = [];
  25. foreach ($items as $delta => $item) {
  26. // return nothing if target_id is null
  27. if(!$item->target_id) return;
  28. $term = Term::load($item->target_id);
  29. // translate the term
  30. $term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $language);
  31. $elements[$delta] = [
  32. // We create a render array to produce the desired markup,
  33. // "<p style="color: #hexcolor">The color code ... #hexcolor</p>".
  34. // See theme_html_tag().
  35. '#type' => 'html_tag',
  36. '#tag' => 'span',
  37. '#value' => $this->t('@target : @location', [
  38. '@target' => $term->getName(),
  39. '@location' => $item->location
  40. ]
  41. ),
  42. ];
  43. }
  44. return $elements;
  45. }
  46. }