You are here

public function LayoutBuilderFieldSerializer::onSerializeContentField in Acquia Content Hub 8.2

Prepare layout builder field.

Parameters

\Drupal\acquia_contenthub\Event\SerializeCdfEntityFieldEvent $event: The content entity field serialization event.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

File

src/EventSubscriber/SerializeContentField/LayoutBuilderFieldSerializer.php, line 55

Class

LayoutBuilderFieldSerializer
Subscribes to entity field serialization to handle layout builder fields.

Namespace

Drupal\acquia_contenthub\EventSubscriber\SerializeContentField

Code

public function onSerializeContentField(SerializeCdfEntityFieldEvent $event) {
  $event_field_type = $event
    ->getField()
    ->getFieldDefinition()
    ->getType();
  if ($event_field_type !== self::FIELD_TYPE) {
    return;
  }
  $this
    ->setFieldMetaData($event);
  $data = [];

  /** @var \Drupal\Core\Entity\TranslatableInterface $entity */
  $entity = $event
    ->getEntity();
  foreach ($entity
    ->getTranslationLanguages() as $langcode => $language) {
    $field = $event
      ->getFieldTranslation($langcode);
    if ($field
      ->isEmpty()) {
      $data['value'][$langcode] = [];
      continue;
    }
    $sections = [];
    foreach ($field as $item) {
      $sections[] = $item
        ->getValue()['section'];
    }
    $sections = $this
      ->serializeSections(...$sections);
    foreach ($sections as $section) {
      $data['value'][$langcode][] = [
        'section' => $section,
      ];
    }
  }
  $event
    ->setFieldData($data);
  $event
    ->stopPropagation();
}