Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| PrimaryEntityReferenceLabelFormatter | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |
100.00% |
1 / 1 |
| viewElements | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Drupal\primary_entity_reference\Plugin\Field\FieldFormatter; |
| 6 | |
| 7 | use Drupal\Core\Field\Attribute\FieldFormatter; |
| 8 | use Drupal\Core\Field\FieldItemListInterface; |
| 9 | use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter; |
| 10 | use Drupal\Core\StringTranslation\TranslatableMarkup; |
| 11 | |
| 12 | /** |
| 13 | * Plugin implementation of the 'primary_entity_reference_label' formatter. |
| 14 | * |
| 15 | * Displays only the primary item's label from a primary entity reference |
| 16 | * field. |
| 17 | */ |
| 18 | #[FieldFormatter( |
| 19 | id: 'primary_entity_reference_label', |
| 20 | label: new TranslatableMarkup('Label (Primary Only)'), |
| 21 | description: new TranslatableMarkup('Display the label of the primary referenced entity.'), |
| 22 | field_types: ['primary_entity_reference'], |
| 23 | )] |
| 24 | class PrimaryEntityReferenceLabelFormatter extends EntityReferenceLabelFormatter { |
| 25 | |
| 26 | /** |
| 27 | * {@inheritdoc} |
| 28 | */ |
| 29 | public function viewElements(FieldItemListInterface $items, $langcode) { |
| 30 | // Get the primary item from the field. |
| 31 | $primary = $items->primary(); |
| 32 | |
| 33 | // Return empty array if no primary item exists. |
| 34 | if (!$primary) { |
| 35 | return []; |
| 36 | } |
| 37 | |
| 38 | // Clone the items list and set only the primary value to avoid mutating |
| 39 | // the original field data. |
| 40 | $primary_items = clone $items; |
| 41 | $primary_items->setValue([$primary->getValue()]); |
| 42 | |
| 43 | // Delegate to parent formatter for actual rendering. |
| 44 | return parent::viewElements($primary_items, $langcode); |
| 45 | } |
| 46 | |
| 47 | } |