EntityReferenceIdFormatter.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
  3. use Drupal\Core\Field\FieldItemListInterface;
  4. /**
  5. * Plugin implementation of the 'entity reference ID' formatter.
  6. *
  7. * @FieldFormatter(
  8. * id = "entity_reference_entity_id",
  9. * label = @Translation("Entity ID"),
  10. * description = @Translation("Display the ID of the referenced entities."),
  11. * field_types = {
  12. * "entity_reference"
  13. * }
  14. * )
  15. */
  16. class EntityReferenceIdFormatter extends EntityReferenceFormatterBase {
  17. /**
  18. * {@inheritdoc}
  19. */
  20. public function viewElements(FieldItemListInterface $items, $langcode) {
  21. $elements = [];
  22. foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
  23. if ($entity->id()) {
  24. $elements[$delta] = [
  25. '#plain_text' => $entity->id(),
  26. // Create a cache tag entry for the referenced entity. In the case
  27. // that the referenced entity is deleted, the cache for referring
  28. // entities must be cleared.
  29. '#cache' => [
  30. 'tags' => $entity->getCacheTags(),
  31. ],
  32. ];
  33. }
  34. }
  35. return $elements;
  36. }
  37. }