You are here

public function ParagraphsPreviewController::onForm in Paragraphs Previewer 8

Render a preview while on a form.

This callback is mapped to the path 'paragraphs-previewer/form/{form_build_id}.

Usage: 'paragraphs-previewer/form/abcd1234?p[0]=field_name&p[1]=delta'.

Parameters

string $form_build_id: The form build id.

string|array $element_parents: The item parents argument from the field to the item delta.

Return value

array The render array.

Throws

\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException If the parameters are invalid.

1 string reference to 'ParagraphsPreviewController::onForm'
paragraphs_previewer.routing.yml in ./paragraphs_previewer.routing.yml
paragraphs_previewer.routing.yml

File

src/Controller/ParagraphsPreviewController.php, line 39

Class

ParagraphsPreviewController
Previewer for paragraphs.

Namespace

Drupal\paragraphs_previewer\Controller

Code

public function onForm($form_build_id, $element_parents) {

  // Parameter check.
  if (empty($form_build_id) || empty($element_parents)) {
    throw new AccessDeniedHttpException();
  }

  // Initialize render array.
  $output_render = [];

  // Expand element parents.
  $element_parents_array = is_array($element_parents) ? $element_parents : explode(':', $element_parents);
  if (!empty($element_parents_array) && count($element_parents_array) >= 2) {
    $form_state = new FormState();
    $form = \Drupal::formBuilder()
      ->getCache($form_build_id, $form_state);
    if ($form && ($form_entity = $form_state
      ->getFormObject()
      ->getEntity())) {
      $field_parents = $element_parents_array;
      $field_delta = array_pop($field_parents);
      $field_name = array_pop($field_parents);
      $widget_state = WidgetBase::getWidgetState($field_parents, $field_name, $form_state);
      if (!empty($widget_state['paragraphs'][$field_delta]['entity'])) {
        $paragraph = $widget_state['paragraphs'][$field_delta]['entity'];
        $parent_entity = $this
          ->findParentEntity($paragraph, $field_parents, $form_state, $form_entity);
        if ($parent_entity) {
          $field_render = $this
            ->paragraphsPreviewRenderParentField($paragraph, $field_name, $parent_entity);
          if ($field_render) {
            $output_render['preview'] = $field_render;
          }
        }
      }
    }
  }

  // Set empty message if nothing is rendered.
  if (empty($output_render)) {
    $output_render['empty'] = [
      '#markup' => $this
        ->t('No preview available.'),
    ];
  }

  // Add styles to cleanup display.
  $output_render['#attached']['library'][] = 'paragraphs_previewer/preview-page';
  return $output_render;
}