Newer
Older
Dries Buytaert
committed
<?php
/**
* @file
Alex Pott
committed
* Contains \Drupal\entity_reference\Plugin\Field\FieldFormatter\EntityReferenceIdFormatter.
Dries Buytaert
committed
*/
Alex Pott
committed
namespace Drupal\entity_reference\Plugin\Field\FieldFormatter;
Dries Buytaert
committed
Alex Pott
committed
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Component\Utility\String;
Dries Buytaert
committed
/**
* Plugin implementation of the 'entity reference ID' formatter.
*
Alex Pott
committed
* @FieldFormatter(
Dries Buytaert
committed
* id = "entity_reference_entity_id",
* label = @Translation("Entity ID"),
* description = @Translation("Display the ID of the referenced entities."),
* field_types = {
* "entity_reference"
* }
* )
*/
class EntityReferenceIdFormatter extends EntityReferenceFormatterBase {
/**
Alex Pott
committed
* {@inheritdoc}
Dries Buytaert
committed
*/
public function viewElements(FieldItemListInterface $items) {
Dries Buytaert
committed
$elements = array();
foreach ($items as $delta => $item) {
catch
committed
if (!$item->access) {
// User doesn't have access to the referenced entity.
continue;
}
Dries Buytaert
committed
if (!empty($item->entity) && !empty($item->target_id)) {
/** @var $referenced_entity \Drupal\Core\Entity\EntityInterface */
$referenced_entity = $item->entity;
$elements[$delta] = array(
'#markup' => String::checkPlain($item->target_id),
// Create a cache tag entry for the referenced entity. In the case
// that the referenced entity is deleted, the cache for referring
// entities must be cleared.
'#cache' => array(
'tags' => $referenced_entity->getCacheTag(),
),
);
Dries Buytaert
committed
}
}
return $elements;
}
}