On hook_block_view_alter() I need to get a total number of rows that this block displays.

For example, I have a view with the following block:

enter image description here

On hook_block_view_alter() I do the appropriate checks in order to weed out unnecessary blocks and get the one shown in the figure above.

function mymodule_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  if (!preg_match('~^views_block:taxonomy_tag_list~', $block->getPluginId())) {

  $view = $block->getViewExecutable();
  // Gets the number of rows
  $totalRows = $view->get_total_rows;

But for some reason, $totalRows contains NULL.enter image description here

Here is the object of the current view: enter image description here

Why can't I get the total number of rows? Maybe I'm using the wrong hook?

  • 1
    just curious, why you don't use HEADER (add) in this views display - you can select there "Result summary" with default content "Displaying start - end of total", plus many other tokens related to the current views, and replace with what you want (bold here should be prepended with @ sign but editor here recognize the sign as reference to a user) – svetlio Jan 20 at 18:25

Use a views_view_ hook, i.e. views_view_unformatted, views_view_list etc... I tried this with a PHP count for my views block and it worked great.

enter image description here

My function is:

function MYTHEME_preprocess_views_view_unformatted(&$vars) {
  $num_rows = $vars["rows"];
  $count = count($num_rows);
  echo '<h2>This view has ' . $count . ' rows</h2><br>';

This yielded the number of rows in the view.

Printed, I see:

enter image description here

| improve this answer | |
  • I think no need to loop over $num_rows just use count function like $count = count($num_rows); – berramou Jan 19 at 21:40
  • @berramou Good idea, answer tested and updated. – Danny Englander Jan 20 at 18:07

No need for any hook.

Adding {{ view.total_rows }} in any views template, eg views-view.html.twig is enough

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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