function NodeNewComments::preRender

Same name in other branches
  1. 8.9.x core/modules/comment/src/Plugin/views/field/NodeNewComments.php \Drupal\comment\Plugin\views\field\NodeNewComments::preRender()
  2. 10 core/modules/comment/src/Plugin/views/field/NodeNewComments.php \Drupal\comment\Plugin\views\field\NodeNewComments::preRender()
  3. 11.x core/modules/comment/src/Plugin/views/field/NodeNewComments.php \Drupal\comment\Plugin\views\field\NodeNewComments::preRender()

Overrides FieldPluginBase::preRender

File

core/modules/comment/src/Plugin/views/field/NodeNewComments.php, line 139

Class

NodeNewComments
Field handler to display the number of new comments.

Namespace

Drupal\comment\Plugin\views\field

Code

public function preRender(&$values) {
    $user = \Drupal::currentUser();
    if ($user->isAnonymous() || empty($values)) {
        return;
    }
    $nids = [];
    $ids = [];
    foreach ($values as $id => $result) {
        $nids[] = $result->{$this->aliases['nid']};
        $values[$id]->{$this->field_alias} = 0;
        // Create a reference so we can find this record in the values again.
        if (empty($ids[$result->{$this->aliases['nid']}])) {
            $ids[$result->{$this->aliases['nid']}] = [];
        }
        $ids[$result->{$this->aliases['nid']}][] = $id;
    }
    if ($nids) {
        $result = $this->database
            ->query("SELECT [n].[nid], COUNT([c].[cid]) AS [num_comments] FROM {node} [n] INNER JOIN {comment_field_data} [c] ON [n].[nid] = [c].[entity_id] AND [c].[entity_type] = 'node' AND [c].[default_langcode] = 1\n        LEFT JOIN {history} [h] ON [h].[nid] = [n].[nid] AND [h].[uid] = :h_uid WHERE [n].[nid] IN ( :nids[] )\n        AND [c].[changed] > GREATEST(COALESCE([h].[timestamp], :timestamp1), :timestamp2) AND [c].[status] = :status GROUP BY [n].[nid]", [
            ':status' => CommentInterface::PUBLISHED,
            ':h_uid' => $user->id(),
            ':nids[]' => $nids,
            ':timestamp1' => HISTORY_READ_LIMIT,
            ':timestamp2' => HISTORY_READ_LIMIT,
        ]);
        foreach ($result as $node) {
            foreach ($ids[$node->nid] as $id) {
                $values[$id]->{$this->field_alias} = $node->num_comments;
            }
        }
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.