Last active
May 28, 2021 20:20
-
-
Save fredysan/47429714eeb89951d8f4674c537c9fd4 to your computer and use it in GitHub Desktop.
Views formatter that concatenates the names of referenced entities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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