You are here

public function AjaxCommentsController::saveReply in AJAX Comments 8

Builds ajax response to save a submitted reply to another comment.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The current request object.

\Drupal\Core\Entity\EntityInterface $entity: The entity this comment belongs to.

string $field_name: The field_name to which the comment belongs.

int $pid: The parent comment's comment ID.

Return value

\Drupal\Core\Ajax\AjaxResponse The Ajax response.

1 string reference to 'AjaxCommentsController::saveReply'
ajax_comments.routing.yml in ./ajax_comments.routing.yml
ajax_comments.routing.yml

File

src/Controller/AjaxCommentsController.php, line 779

Class

AjaxCommentsController
Controller routines for AJAX comments routes.

Namespace

Drupal\ajax_comments\Controller

Code

public function saveReply(Request $request, EntityInterface $entity, $field_name, $pid) {
  $response = new AjaxResponse();

  // Check the user's access to reply.
  // The user should not have made it this far without proper permission,
  // but adding this access check as a fallback.
  $this
    ->replyAccess($request, $response, $entity, $field_name, $pid);

  // If $this->replyAccess() added any commands to the AjaxResponse,
  // it means that access was denied, so we should NOT submit the form
  // and rebuild the comment field. Instead, return the response
  // immediately and abort the save.
  if (!empty($response
    ->getCommands())) {
    return $response;
  }

  // Build a dummy comment entity to pass to $this->save(), which will use
  // it to rebuild the comment entity form to trigger form submission.
  // @code
  // $form = $this->entityFormBuilder()->getForm($comment, 'default', ['editing' => TRUE]);
  // @endcode
  // Note that this approach will correctly process the form submission
  // even though we are passing in an empty, dummy comment, because two steps
  // later in the call stack, \Drupal\Core\Form\FormBuilder::buildForm() is
  // called, and it checks the current request object for form submission
  // values if there aren't any in the form state, yet:
  // @code
  // $input = $form_state->getUserInput();
  // if (!isset($input)) {
  //   $input = $form_state->isMethodType('get') ? $request->query->all() : $request->request->all();
  //   $form_state->setUserInput($input);
  // }
  // @endcode
  // This approach is very similar to the one taken in
  // \Drupal\comment\CommentLazyBuilders::renderForm().
  $comment = $this
    ->entityTypeManager()
    ->getStorage('comment')
    ->create([
    'entity_id' => $entity
      ->id(),
    'pid' => $pid,
    'entity_type' => $entity
      ->getEntityTypeId(),
    'field_name' => $field_name,
  ]);

  // Rebuild the form to trigger form submission.
  return $this
    ->save($request, $comment);
}