4

I set up a content type and a specific comment type for this content. I set the comment pager to display 10 comments per page. When I now use the pager, I get redirected from the node URL itself www.domain.com/node/1, to www.domain.com/node/1?page=1.

Is there any possibility to add an ID to the URL for the comments pager only, for example www.domain.com/node/1?page=1#comments?

I want to do this, so the user doesn't need to scroll over the whole content of the node again, just to get to the second comments page. Instead, I want to jump to the comment section right away.

Is there any elegant way to do so? A module that does it, or similar? I already thought of altering the pager.html.twig in my theme. But then I would alter the node pager as well. Thank you very much in advance for pointing me any way to achieve this.

2 Answers 2

2

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;
}
1
  • Thank you very much! This would have taken me ages to figure out. Commented Oct 18, 2020 at 15:41
0

You could use template_preprocess_pager(), but I am not sure you will be able to target one specific pager. You should check in $variables if there's any ID you can use to target the comment pager.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.