You are here

public function EntityReferenceFacetFormatterBase::viewElements in Entity Reference Facet Link 8

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/EntityReferenceFacetFormatterBase.php, line 146

Class

EntityReferenceFacetFormatterBase

Namespace

Drupal\entity_reference_facet_link\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $facet = $this
    ->getFacet();
  if (empty($facet)) {
    return [];
  }

  // Instead of trying to guess how the facet URLs should be formatted, let
  // the facet's own URL processor do the work of building them.  Then the
  // URLs will be formatted correctly no matter what processor is being used,
  // for instance Facets Pretty Paths.
  $url_processor_id = $facet
    ->getFacetSourceConfig()
    ->getUrlProcessorName();
  $configuration = [
    'facet' => $facet,
  ];

  /** @var \Drupal\facets\UrlProcessor\UrlProcessorInterface $url_processor */
  $url_processor = $this->urlProcessorPluginManager
    ->createInstance($url_processor_id, $configuration);
  $elements = [];
  foreach ($this
    ->getEntitiesToView($items, $langcode) as $delta => $entity) {

    // Create a fake Result object from the field item so that we can pass
    // it to the URL processor.
    $result = new Result($facet, $entity
      ->id(), $entity
      ->label(), 0);
    $result = $url_processor
      ->buildUrls($facet, [
      $result,
    ])[0];

    // Invalidate the cache when the referenced entity or the facet source
    // config changes.  The source display config, for instance a view, should
    // be added here too, but there really isn't any way to access that config
    // entity through the API.
    $cache_tags = Cache::mergeTags($entity
      ->getCacheTags(), $facet
      ->getFacetSourceConfig()
      ->getCacheTags());
    $elements[$delta] = $this
      ->buildElement($result
      ->getUrl(), $entity) + [
      '#cache' => [
        'tags' => $cache_tags,
      ],
    ];
  }
  return $elements;
}