You are here

public function ParagraphsPreviewController::findParentEntity in Paragraphs Previewer 8

Find the parent entity of the paragraph.

Finds any parent paragraphs else defaults to the form entity provided. Note: only paragraphs are supported as parent or intermediate entities.

Parameters

\Drupal\paragraphs\Entity\Paragraph $paragraph: The paragraph entity.

array $field_parents: The field parents of the paragraph.

\Drupal\Core\Form\FormStateInterface $form_state: The form state.

\Drupal\Core\Entity\EntityInterface $form_entity: The form entity.

Return value

\Drupal\Core\Entity\EntityInterface The parent entity if found else the form entity.

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

File

src/Controller/ParagraphsPreviewController.php, line 105

Class

ParagraphsPreviewController
Previewer for paragraphs.

Namespace

Drupal\paragraphs_previewer\Controller

Code

public function findParentEntity(Paragraph $paragraph, array $field_parents, FormStateInterface $form_state, EntityInterface $form_entity = NULL) {
  if (in_array('subform', $field_parents, TRUE)) {

    // Traverse up to find the parent.
    foreach (array_reverse($field_parents, TRUE) as $i => $element_key) {
      if ($element_key === 'subform') {

        // Slice one level above 'subform'.
        $parent_field_parents = array_slice($field_parents, 0, $i);
        if ($parent_field_parents) {
          $parent_field_delta = array_pop($parent_field_parents);
          $parent_field_name = array_pop($parent_field_parents);
          $widget_state = WidgetBase::getWidgetState($parent_field_parents, $parent_field_name, $form_state);
          if (!empty($widget_state['paragraphs'][$parent_field_delta]['entity'])) {

            // Return first found.
            return $widget_state['paragraphs'][$parent_field_delta]['entity'];
          }
        }

        // Break on first found.
        break;
      }
    }
  }
  return $form_entity;
}