Skip to content

Instantly share code, notes, and snippets.

@fredysan
Last active May 28, 2021 20:20
Show Gist options
  • Save fredysan/47429714eeb89951d8f4674c537c9fd4 to your computer and use it in GitHub Desktop.
Save fredysan/47429714eeb89951d8f4674c537c9fd4 to your computer and use it in GitHub Desktop.
Views formatter that concatenates the names of referenced entities
<?php
/**
* @file
*/
namespace Drupal\my_module\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
/**
* Plugin implementation of the 'Referenced entity names' views field formatter.
*
* @FieldFormatter(
* id = "referenced_entity_names_field_formatter",
* label = @Translation("Referenced entity names"),
* field_types = {
* "entity_reference"
* }
* )
*/
class ReferencedEntityNamesFieldFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
foreach ($items as $delta => $item) {
if (is_object($item->entity->target_id->entity)) {
$element[$delta] = ['#markup' => $item->entity->target_id->entity->name->value];
}
}
return $element;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment