function CommentForm::preview

Same name and namespace in other branches
  1. 11.x core/modules/comment/src/CommentForm.php \Drupal\comment\CommentForm::preview()
  2. 10 core/modules/comment/src/CommentForm.php \Drupal\comment\CommentForm::preview()
  3. 9 core/modules/comment/src/CommentForm.php \Drupal\comment\CommentForm::preview()
  4. 8.9.x core/modules/comment/src/CommentForm.php \Drupal\comment\CommentForm::preview()

Form submission handler for the 'preview' action.

Parameters

array $form: An associative array containing the structure of the form.

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

File

core/modules/comment/src/CommentForm.php, line 362

Class

CommentForm
Base handler for comment forms.

Namespace

Drupal\comment

Code

public function preview(array &$form, FormStateInterface $form_state) {
  $comment_preview = [];
  $comment = $this->entity;
  $entity = $comment->getCommentedEntity();
  if (!$form_state->getErrors()) {
    $comment->in_preview = TRUE;
    $comment_build = $this->entityTypeManager
      ->getViewBuilder('comment')
      ->view($comment);
    $comment_build['#weight'] = -100;
    $comment_preview['comment_preview'] = $comment_build;
  }
  if ($comment->hasParentComment()) {
    $build = [];
    $parent = $comment->getParentComment();
    if ($parent && $parent->isPublished()) {
      $build = $this->entityTypeManager
        ->getViewBuilder('comment')
        ->view($parent);
    }
  }
  else {
    // The comment field output includes rendering the parent entity of the
    // thread to which the comment is a reply. The rendered entity output
    // includes the comment reply form, which contains the comment preview and
    // therefore the rendered parent entity. This results in an infinite loop
    // of parent entity output rendering the comment form and the comment form
    // rendering the parent entity. To prevent this infinite loop we
    // temporarily set the value of the comment field on a clone of the entity
    // to hidden before calling the entity view builder. That way when the
    // output of the commented entity is rendered, it excludes the comment
    // field output.
    $field_name = $comment->getFieldName();
    $entity = clone $entity;
    $entity->{$field_name}->status = CommentItemInterface::HIDDEN;
    $build = $this->entityTypeManager
      ->getViewBuilder($entity->getEntityTypeId())
      ->view($entity);
  }
  $comment_preview['comment_output_below'] = $build;
  $comment_preview['comment_output_below']['#weight'] = 200;
  $comment_preview['#title'] = $this->t('Preview comment');
  $form_state->set('comment_preview', $comment_preview);
  $form_state->setRebuild();
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.