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