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
    Commented Jan 20, 2020 at 18:25

3 Answers 3


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

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

No need for any hook.

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


No need for any coding. Edit the view and under "Header" or "Footer" add a "Text area" (Category: Global) and see the available global token replacements.

To get the total number of rows add: [view:total-rows] and save the view.

  • You're right, it's very simple with the token. But the limit is that we cannot make conditions. I needed it to handle the singular/plural of the text displayed after the counter. Commented Jan 5 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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