public function EntityReferenceExportFormatter::view in REST Views 2.0.x
Same name and namespace in other branches
- 8 src/Plugin/Field/FieldFormatter/EntityReferenceExportFormatter.php \Drupal\rest_views\Plugin\Field\FieldFormatter\EntityReferenceExportFormatter::view()
Overrides EntityReferenceFormatterBase::view
See also
::prepareView()
::getEntitiesToView()
File
- src/
Plugin/ Field/ FieldFormatter/ EntityReferenceExportFormatter.php, line 31
Class
- EntityReferenceExportFormatter
- A plugin that creates a serializable form of a rendered entity.
Namespace
Drupal\rest_views\Plugin\Field\FieldFormatterCode
public function view(FieldItemListInterface $items, $langcode = NULL) {
$elements = $this
->viewElements($items, $langcode);
$output = [
'#items' => $items,
];
$entity_key = '#' . $this
->getFieldSetting('target_type');
$extra = $this
->getSetting('extra');
foreach ($elements as $delta => $row) {
$output[$delta] = [];
// Entities build their fields in a pre-render function.
if (isset($row['#pre_render'])) {
foreach ((array) $row['#pre_render'] as $callable) {
$row = $callable($row);
}
}
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $row[$entity_key];
if (!empty($extra['id'])) {
$output[$delta]['id'] = $entity
->id();
}
if (!empty($extra['title'])) {
$output[$delta]['title'] = $entity
->label();
}
if (!empty($extra['url'])) {
try {
$output[$delta]['url'] = $entity
->toUrl()
->setAbsolute()
->toString();
} catch (\Exception $exception) {
$output[$delta]['url'] = NULL;
}
}
if (!empty($extra['type'])) {
$output[$delta]['type'] = $entity
->getEntityTypeId();
}
if (!empty($extra['bundle'])) {
$output[$delta]['bundle'] = $entity
->bundle();
}
// Traverse the fields and build a serializable array.
foreach (Element::children($row) as $name) {
$alias = preg_replace('/^field_/', '', $name);
if (!empty($output[$delta][$alias])) {
continue;
}
$field = $row[$name];
foreach (Element::children($field) as $index) {
$value = $field[$index];
if (isset($value['#type']) && $value['#type'] === 'data') {
$value = SerializedData::create($value['#data']);
}
else {
$value = RenderableData::create($value);
}
$output[$delta][$alias][$index] = $value;
}
// If the field has no multiple cardinality, unpack the array.
if (!empty($field['#items'])) {
/** @var \Drupal\Core\Field\FieldItemListInterface $field_items */
$field_items = $field['#items'];
if (!$field_items
->getFieldDefinition()
->getFieldStorageDefinition()
->isMultiple()) {
$output[$delta][$alias] = reset($output[$delta][$alias]);
}
}
}
$output[$delta] = [
'#type' => 'data',
'#data' => SerializedData::create($output[$delta]),
];
}
return $output;
}