Last post returns wrong data if no comments were posted

Created on 12 November 2018, over 5 years ago
Updated 24 April 2024, 2 months ago

Steps to reproduce:

1/ Setup a forum, a forum category and create 2 users with access to create forum posts.
2/ Create a forum post with user A: the forum overview now shows the latest post was made by user A.
3/ Change the forum post author to user B: the forum overview now still shows the latest post was by user A.

At this point it should show user B has the latest post. User A has absolutely no posts in the forum.

I narrowed this down to the comment_statistics. Which is not updated if you change the author of the original post and there were no comments yet.

I'm using the below code in a custom module to fix this behaviour:


/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function MYMODULE_node_presave(\Drupal\Core\Entity\EntityInterface $entity) {
  /** @var \Drupal\node\Entity\Node $entity */
  if ($entity->bundle() == 'forum') {
    $stats = db_select('comment_entity_statistics', 'ces')
      ->fields('ces')
      ->condition('ces.entity_id', $entity->id())
      ->condition('ces.entity_type', $entity->getEntityTypeId())
      ->condition('ces.comment_count', 0)
      ->execute();
    while ($entry = $stats->fetchObject()) {
      db_merge('comment_entity_statistics')
        ->fields([
          'cid' => $entry->cid,
          'comment_count' => 0,
          'last_comment_timestamp' => $entry->last_comment_timestamp,
          'last_comment_name' => '',
          'last_comment_uid' => $entity->get('uid')->getValue()[0]['target_id'],
        ])
        ->keys([
          'entity_id' => $entity->id(),
          'entity_type' => $entity->getEntityTypeId(),
          'field_name' => $entry->field_name,
        ])
        ->execute();
    }
  }
}
πŸ› Bug report
Status

Active

Version

1.0

Component

forum.module

Created by

πŸ‡§πŸ‡ͺBelgium weseze

Live updates comments and jobs are added and updated live.
  • Needs tests

    The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024