Drupal 5: fix comment permalinks with pagination

Submitted by Janak on Mon, 11/16/2009 - 18:03

having done some more work on making Drupal Froums look nice and work more like a forum, I noticed a potential bug in the way Drupal handles pagination on comments. If you have a node with many comments and you have enabled comment pagination, you will notice:

  • After posting a comment in, you are redirected back to page 1, on a multipaged forum topic this is really annoying.
  • Permalinks to comments do not work because the comment_form_submit does not pass in the query (page number)
  • Changing the comments per page will generate a different permalink for each comment, without creating a dedicated callback and redirecting the user to the specific post (comment/permalink/comment_ID), there doesnt seem to be a fix for this

It is easy enough to redirect the user to (node/NODE_NID?page=PAGE_ID#COMMENT_ID) after a comment gets submitted. Here is what I did:

function mymodule_form_alter($form_id, &$form) {  
  if ($form_id == 'forum_node_form' && $form_id == 'comment_form'){
    $form['#redirect'] = mymodule_comment_redirect($form['nid']['#value']);
function mymodule_comment_redirect($nid){
  global $user;
  $uid = $user->uid;
  //get the last comment ID
  $sql = "SELECT cid FROM {comments} WHERE nid = %d AND uid = %d ORDER BY timestamp DESC LIMIT 1";
  $cid = db_result(db_query($sql, $nid, $uid));  
  //work out totals etc
  $sql2 = "SELECT count(cid) as total FROM {comments} WHERE nid = %d";
  $comment_total = db_result(db_query($sql2, $nid));
  $comment_default_per_page = variable_get('comment_default_per_page', 10);
  $last_page = floor($comment_total/$comment_default_per_page);
  //return the redirect url with fragment pager id
  return array('node/'. $nid, "page=".$last_page, "comment-$cid");