You are here

protected function AjaxCommentsController::renderCommentField in AJAX Comments 8

Build a comment field render array for the ajax response.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity that has the comment field.

string $field_name: The machine name of the comment field.

Return value

array A render array for the updated comment field.

1 call to AjaxCommentsController::renderCommentField()
AjaxCommentsController::buildCommentFieldResponse in src/Controller/AjaxCommentsController.php
Create an ajax response to replace the comment field.

File

src/Controller/AjaxCommentsController.php, line 135

Class

AjaxCommentsController
Controller routines for AJAX comments routes.

Namespace

Drupal\ajax_comments\Controller

Code

protected function renderCommentField(EntityInterface $entity, $field_name) {
  $comment_field = $entity
    ->get($field_name);

  // Load the display settings to ensure that the field formatter
  // configuration is properly applied to the rendered field when it is
  // returned in the ajax response.
  $display_options = $this->entityTypeManager
    ->getStorage('entity_view_display')
    ->load($entity
    ->getEntityTypeId() . '.' . $entity
    ->bundle() . '.default')
    ->getComponent($field_name);
  $comment_display = $comment_field
    ->view($display_options);

  // To avoid infinite nesting of #theme_wrappers elements on subsequent
  // ajax responses, unset them here.
  unset($comment_display['#theme_wrappers']);

  // Remove unneeded route parameters.
  unset($comment_display[0]['comments']['pager']['#route_parameters']['entity_type']);
  unset($comment_display[0]['comments']['pager']['#route_parameters']['entity']);
  unset($comment_display[0]['comments']['pager']['#route_parameters']['field_name']);
  unset($comment_display[0]['comments']['pager']['#route_parameters']['pid']);
  $entity_type = $entity
    ->getEntityType();

  // For replies, the passed $entity is the parent comment.
  // However, for the pager we want the parent entity.
  if ($entity_type
    ->id() === 'comment') {
    $entity = $entity
      ->getCommentedEntity();
    $entity_type = $entity
      ->getEntityType();
  }
  $handler = $this
    ->entityTypeManager()
    ->getRouteProviders($entity_type
    ->id())['html'];
  $route_collection = $handler
    ->getRoutes($entity_type);
  $name = 'entity.' . $entity_type
    ->get('id') . '.canonical';
  $route = $route_collection
    ->get($name);

  // Override the ajax route object with the actual entity route.
  $entity_url = $entity
    ->toURL();
  if ($route) {
    $comment_display[0]['comments']['pager']['#route_name'] = $route;
    $comment_display[0]['comments']['pager']['#route_parameters'] = $entity_url
      ->getRouteParameters();
  }
  return $comment_display;
}