Add function to get the amount of results of a view

Created on 3 June 2024, 8 months ago

Problem/Motivation

Currently, the Views documentation of this module recommends the following snippet to check if the view has results:

{% set view = drupal_view_result('related', 'block_1')|length %}
{% if view > 0 %}
  {{ drupal_view('related', 'block_1') }}
{% endif %}

This isn't optimal performance-wise though: it loads all results of the view, even though we only need a count.

Proposed resolution

I propose adding a drupal_view_result_count function that executes a count query without loading all view results. We should also update the documentation to use the new function:

{% set count = drupal_view_result_count('related', 'block_1') %}
{% if count > 0 %}
  {{ drupal_view('related', 'block_1') }}
{% endif %}
Feature request
Status

Closed: won't fix

Version

3.0

Component

Code

Created by

🇧🇪Belgium dieterholvoet Brussels

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

  • Issue created by @dieterholvoet
  • Merge request !51Add drupal_view_result_count function → (Open) created by dieterholvoet
  • Open in Jenkins → Open on Drupal.org →
    Core: 10.2.x + Environment: PHP 8.1 & MariaDB 10.3.22
    11:35
    8:43
    Running
  • Status changed to Needs review 8 months ago
  • Pipeline finished with Success
    8 months ago
    Total: 150s
    #189800
  • Open in Jenkins → Open on Drupal.org →
    Core: 10.2.x + Environment: PHP 8.1 & MariaDB 10.3.22
    last update 8 months ago
    11 pass
  • Pipeline finished with Success
    8 months ago
    Total: 150s
    #189809
  • Status changed to Closed: won't fix 8 months ago
  • 🇧🇪Belgium dieterholvoet Brussels

    It seems like my implementation doesn't account for paging. Also, I did some basic benchmarking to compare the results of both approaches:

    • TwigTweakExtension::drupalViewResultCount();
    • count(views_get_view_result());

    I ran both functions 3000 times on a view in one of my projects. The first approach took 0.0147 seconds, the second one 0.0101. Weird, but it looks like the count query is slower, even though it's not paged. It also looks like both queries are already very fast, so the result will be negligible - especially when the loaded entities already exist in entity cache.

    I'll close this issue, it's not worth it.

Production build 0.71.5 2024