You are here

public function ParagraphsPreviewController::paragraphsPreviewRenderParentField in Paragraphs Previewer 8

Render a single field on the parent entity for the given paragraph.

Parameters

Paragraph $paragraph: The paragraph entity.

string $parent_field_name: The field name of the paragraph reference field on the parent entity.

ContentEntityBase $parent_entity: Optional. The parent entity. This is used when on a form to allow rendering with un-saved parents.

Return value

array|null A render array for the field.

1 call to ParagraphsPreviewController::paragraphsPreviewRenderParentField()
ParagraphsPreviewController::onForm in src/Controller/ParagraphsPreviewController.php
Render a preview while on a form.

File

src/Controller/ParagraphsPreviewController.php, line 146

Class

ParagraphsPreviewController
Previewer for paragraphs.

Namespace

Drupal\paragraphs_previewer\Controller

Code

public function paragraphsPreviewRenderParentField(Paragraph $paragraph, $parent_field_name, ContentEntityBase $parent_entity = NULL) {
  if (!isset($parent_entity)) {
    $parent_entity = $paragraph
      ->getParentEntity();
  }
  if ($parent_entity && $parent_entity instanceof ContentEntityBase) {
    $parent_class = get_class($parent_entity);
    $parent_entity_type = $parent_entity
      ->getEntityTypeId();
    if ($parent_entity
      ->hasField($parent_field_name)) {
      $parent_view_mode = \Drupal::config('paragraphs_previewer.settings')
        ->get('previewer_view_mode');
      $parent_view_mode = $parent_view_mode ? $parent_view_mode : 'full';

      // Create a new paragraph with no id.
      $paragraph_clone = $paragraph
        ->createDuplicate();

      // Clone the entity since we are going to modify field values.
      $parent_clone = clone $parent_entity;

      // Create field item values.
      $parent_field_item_value = [
        'entity' => $paragraph_clone,
      ];

      // Based on \Drupal\Core\Entity\EntityViewBuilder to allow arbitrary
      // field data to be rendered.
      // See https://www.drupal.org/node/2274169
      // Push the item as the single value for the field, and defer to
      // FieldItemBase::view() to build the render array.
      $parent_clone->{$parent_field_name}
        ->setValue([
        $parent_field_item_value,
      ]);

      // TODO: This clones the parent again and uses
      // EntityViewBuilder::viewFieldItem().
      $elements = $parent_clone->{$parent_field_name}
        ->view($parent_view_mode);

      // Extract the part of the render array we need.
      $output = isset($elements[0]) ? $elements[0] : [];
      if (isset($elements['#access'])) {
        $output['#access'] = $elements['#access'];
      }
      return $output;
    }
  }
}