You are here

public function AjaxCommentsForm::save in AJAX Comments 8

Override the redirect set by \Drupal\comment\CommentForm::save().

Drupal needs to redirect the form back to itself so that processing completes and the new comments appears in the markup returned by the ajax response. If we merely unset the redirect to the node page, the new comment will not appear until the next page refresh.

Parameters

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

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

Overrides CommentForm::save

File

src/Form/AjaxCommentsForm.php, line 401

Class

AjaxCommentsForm
Provides ajax enhancements to core default Comment form.

Namespace

Drupal\ajax_comments\Form

Code

public function save(array $form, FormStateInterface $form_state) {
  parent::save($form, $form_state);

  /** @var \Drupal\comment\CommentInterface $comment */
  $comment = $form_state
    ->getFormObject()
    ->getEntity();
  $comment_formatter = $this->fieldSettingsHelper
    ->getFieldFormatterFromComment($comment, 'full');
  if (empty($comment_formatter) || !$this->fieldSettingsHelper
    ->isEnabled($comment_formatter)) {

    // If not using Ajax Comments, do not change the redirect.
    return;
  }

  // Save the comment id in the private tempStore, so that the controller
  // can access it in a subsequent HTTP request.
  $this->tempStore
    ->setCid($comment
    ->id());

  // Code adapted from FormSubmitter::redirectForm().
  $request = $this->requestStack
    ->getCurrentRequest();
  $route_name = RouteMatch::createFromRequest($request)
    ->getRouteName();
  if (!in_array($route_name, [
    'entity.comment.edit_form',
    'comment.reply',
  ])) {
    $form_state
      ->setRedirect('<current>', [], [
      'query' => $request->query
        ->all(),
      'absolute' => TRUE,
    ]);
  }
}