How to add view total row count as a field in views page or rest displays in Drupal

Here we are discussing about  how to add views total row count as another field in view page/ rest export.

Developers need to write logic at the front end based on the total number of rows available in Rest Export if pagination enabled. Same steps can be used with other than Rest export displays.

We have a view which has Rest export display.

Now click on add field. Search for custom text field as below.

Click Apply. You can add label to the field.

You can see this fields as ‘nothing’ in your View Rest response.

Here you can see view row count as 5 in nothing field. Next we are discussing how to add this view rows count to the nothing field.

For achieving this create *.module file in your custom module. 

Import views first.

<?php
use Drupal\views\Views;

Then create a view_pre_render hook as below.

function modulename_views_pre_render(&$view) {
}

Next inside this hook function  check for which view id getting loaded and also check with our  display id as below. Here our view id is dn_app_people and display id is rest_export_1.

if( $view->id() == 'dn_app_people' && $view->current_display == 'rest_export_1'){
}

If it is the same  we have to  add total rows of view to the nothing field, we have to fine  total rows of our  view as below.

$view1 = Views::getView('dn_app_people');
   $view1->get_total_rows = TRUE;
   $view1->execute('rest_export_1');
   $rows = $view1->total_rows;

Next assign this count $rows to the nothing field as below.

$view->field['nothing']->options['alter']['text'] = $rows;

So complete hook will be looks  like this.

<?php
use Drupal\views\Views;

function drupal_admin_app_views_pre_render(&$view) {

 if( $view->id() == 'dn_app_people' && $view->current_display == 'rest_export_1'){
   
    $view1 = Views::getView('dn_app_people');
   $view1->get_total_rows = TRUE;
   $view1->execute('rest_export_1');
   $rows = $view1->total_rows;
   
   $view->field['nothing']->options['alter']['text'] = $rows;


 }

}

Clear the cache, you can see the total views rows count in nothing field of the view.

Get Free E-book
Get a free Ebook on Drupal 8 -theme tutorial
I agree to have my personal information transfered to MailChimp ( more information )
if you like this article Buy me a Coffee this will be an ispiration for me to write articles like this.

You may also like...