Drupal - Alter comment pager to jump to comment section right away?

The only hook Drupal uses to alter a pager is hook_preprocess_pager() but that is invoked for every pager on any page, not just the pager used for comments.

The alternative is adding a new formatter for comments, which by default is the CommentDefaultFormatter class, and make it the default one with hook_field_info_alter().

function mymodule_field_info_alter(&$info) {
  // Change the default widget for fields of type 'comment'.
  if (isset($info['comment'])) {
    $info['comment']['default_formatter'] = 'mymodule_comment_formatter';
  }
}

(mymodule_comment_formatter is the formatter ID used in its annotation.)

The relevant code that sets the pager is in CommentDefaultFormatter::viewElements(), which contains the following lines.

if ($comments) {
  $build = $this->viewBuilder->viewMultiple($comments, $this->getSetting('view_mode'));
  $build['pager']['#type'] = 'pager';

  // CommentController::commentPermalink() calculates the page number
  // where a specific comment appears and does a subrequest pointing to
  // that page, we need to pass that subrequest route to our pager to
  // keep the pager working.
  $build['pager']['#route_name'] = $this->routeMatch->getRouteObject();
  $build['pager']['#route_parameters'] = $this->routeMatch->getRawParameters()->all();
  if ($this->getSetting('pager_id')) {
    $build['pager']['#element'] = $this->getSetting('pager_id');
  }
  $output['comments'] += $build;
}

Tags:

Paging

Comments

9