Provide an EntityReferenceFieldItemNormalizer with options to return content entity labels and config entity IDs.
This commit is contained in:
parent
59802748e8
commit
9995efd994
|
@ -4,3 +4,8 @@ services:
|
|||
tags:
|
||||
- { name: normalizer, priority: 10 }
|
||||
arguments: ['@entity_type.manager', '@entity_type.repository', '@entity_field.manager']
|
||||
farm_csv.normalizer.entity_reference_field_item:
|
||||
class: Drupal\farm_csv\Normalizer\EntityReferenceFieldItemNormalizer
|
||||
tags:
|
||||
- { name: normalizer, priority: 10 }
|
||||
arguments: ['@entity.repository']
|
||||
|
|
|
@ -0,0 +1,51 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\farm_csv\Normalizer;
|
||||
|
||||
use Drupal\Core\Config\Entity\ConfigEntityInterface;
|
||||
use Drupal\Core\Entity\ContentEntityInterface;
|
||||
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItemInterface;
|
||||
use Drupal\serialization\Normalizer\EntityReferenceFieldItemNormalizer as CoreEntityReferenceFieldItemNormalizer;
|
||||
|
||||
/**
|
||||
* Normalizes entity reference fields for farmOS CSV exports.
|
||||
*/
|
||||
class EntityReferenceFieldItemNormalizer extends CoreEntityReferenceFieldItemNormalizer {
|
||||
|
||||
/**
|
||||
* The supported format.
|
||||
*/
|
||||
const FORMAT = 'csv';
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function normalize($field_item, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
|
||||
|
||||
// Attempt to load the referenced entity.
|
||||
/** @var \Drupal\Core\Entity\EntityInterface $entity */
|
||||
if ($entity = $field_item->get('entity')->getValue()) {
|
||||
|
||||
// Return content entity labels, if desired.
|
||||
if ($entity instanceof ContentEntityInterface && !empty($context['content_entity_labels'])) {
|
||||
return $entity->label();
|
||||
}
|
||||
|
||||
// Return config entity IDs, if desired.
|
||||
if ($entity instanceof ConfigEntityInterface && !empty($context['config_entity_ids'])) {
|
||||
return $entity->id();
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, delegate to the parent method.
|
||||
return parent::normalize($field_item, $format, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function supportsNormalization($data, string $format = NULL, array $context = []): bool {
|
||||
return $data instanceof EntityReferenceItemInterface && $format == static::FORMAT;
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue