I have a view setup with external filters that query a list of nodes. I've tried to cobble together some PHP to place a count of the number of results returned in the footer of the Views page—to no avail.

It seems simple enough; does anybody have an idea about how to do this, or know of the necessary code?

Thanks!!!

Comments

mooffie’s picture

I see two solutions:

1. Set the view's footer format to PHP and there print the $GLOBALS['pager_total_items'][0] variable.

2. Views records the number of rows in the $view->total_rows_rows variable. Implement hook_views_post_view to return a message containing this value.

sillygwailo’s picture

The following, in the footer, works for me, for views that don't have a pager:

print $GLOBALS['current_view']->num_rows;

For views that do have a pager, I use the following:

print $GLOBALS['current_view']->total_rows;

(Username formerly my full name, Richard Eriksson.)

codenamerhubarb’s picture

Here's what I did to make it show a result like the following:

"Showing X to X of X results" or just "X results" if it doesn't go over the one page.

 if ($GLOBALS['current_view']->total_rows <= 15) {
  echo "<b>" . $GLOBALS['current_view']->total_rows . "</b> results";
  }else{
  echo "Showing 1-15 of <b>" . $GLOBALS['current_view']->total_rows . "</b> results";
  }
  

My views are set to 15 results per page so obviously you'll have to change the number 15 to however many you have in your view. You can see a real life example by going here.

-------------------------------
My Drupal site: Download a Book.

kingandy’s picture

I've tried to adapt this to number the actual items shown (instead of 1-15, which won't be true once you're off the first page even if you do change it to the right number of items ;)) ... Unfortunately the global $current_view doesn't actually tell you what page you're on. You can get this value, however, either through $_GET['page'] or $GLOBALS['pager_page_array'][0]. In fact you can also get the number of items from the pager ($GLOBALS['pager_total_items'][0]), as well as the number of pages ($GLOBALS['pager_total'][0]), so if only it would also give you the number of items per page, I'd almost suggest using that instead of the current_view. Unfortunately, as it is, we have to fish from both pools.

 // Lift the globals into local scope to save typing $GLOBALS[''] every time...
global $pager_page_array, $pager_total_items, $pager_total, $current_view;

if ($pager_total[0] == 1) { // Number of pages == 1
  echo "Showing <b>" . $pager_total_items[0] . "</b> results";
}else{
  // Page number is zero-based (first page is 0)
  // Multiply pager_limit by page number (eg 0, 15, 30) and add 1 to get first item
  $start = 1 + ($pager_page_array[0] * $current_view->pager_limit);
  // Multiply pager_limit by page number + 1 (eg 15, 30, 45) to get last item
  $end = (1 + $pager_page_array[0]) * $current_view->pager_limit;
  // Use total items count if this is less than that
  if ($end > $pager_total_items[0]) $end = $pager_total_items[0];
  echo "Showing $start-$end of <b>" . $pager_total_items[0] . "</b> results";
}

--Andy
Developing Drupal websites for Livelink New Media

++Andy
Developing Drupal websites for Livelink New Media since 2008

doc2@drupalfr.org’s picture

Andy, this is a great snippet which works out-of-the-box! Thank you very much.

codenamerhubarb’s picture

Thanks kingandy, this really works great!

-------------------------------
My Drupal site which I love to pieces: Download a Book.

-------------------------------
My Drupal site: Download a Book.

eblues’s picture

I'm using Views v6.x-2.1 and most of the code posted in this thread does not seem to work for me. All I want to do is show the total number of results for each query, regardless of how many pages are required to display.

If this is a version discrepancy, where can I find info on the correct variables to use?

thanks,
Herm

kingandy’s picture

I'm afraid I know nothing about Drupal 6.x and less about Views 2.x. However, down the page moofie suggests views_get_current_view() as a replacement for global $current_view.

A quick look at the docs (specifically pager_query()) indicates that the globals $pager_page_array, $pager_total_items and $pager_total are still there, but whether they work the same as they did in 5.x is unknown to me. The code looks pretty identical though.

So, assuming the actual view structure is unchanged, it might be as simple as changing the first few lines like so:

global $pager_page_array, $pager_total_items, $pager_total;
$current_view = views_get_current_view();

Otherwise ... ehh ... I guess you'll have to do a print '<pre>'. print_r($current_view, true) .'</pre>'; and squint at the new view structure until you find something that resembles the number of items per page. Beyond that, you're on your own...

++Andy
Developing Drupal websites for Livelink New Media since 2008

eblues’s picture

Thanks to Andy and Moofie. I'm afraid this is still a bit out of my league.

I tried replacing the lines Andy suggested, but wasn't able to get anything out of views_get_current_view(). echo print_r($current_view, true) yielded no output, as did echo print_r($views_get_current_view, true). Dropping the true parameter they both give a result of 1, whatever that indicates.

$pager_total_items gives the value I want (query results count), but only if paging is used. So I'm still lacking a way to show the query results count when paging is not used. For now I'll just use paging on views displays when I want to show the results count. Hopefully I'll stumble across a solution for non-paged views eventually.

thanks again for the input.

matteo.boria’s picture

Code of kingandy adapted. Same behaviour. For contextual use (e.g.: in footer or header).

global $pager_page_array, $pager_total_items, $pager_total;
$my_view = views_get_current_view();
$items_per_page = $my_view->pager['items_per_page'];
if ($pager_total[0] == 1) {
  echo "Showing <b>" . $pager_total_items[0] . "</b> results";
} else {
  $start = 1 + ($pager_page_array[0] * $items_per_page);
  $end = (1 + $pager_page_array[0]) * $items_per_page;
  if ($end > $pager_total_items[0]) $end = $pager_total_items[0];
  echo "Showing $start-$end of <b>" . $pager_total_items[0] . "</b> results";
}
kingandy’s picture

Looking at this now I suddenly realise I've been remiss in my internationalisation ... each of those 'echo' calls should be run through the t() function before display. Something like:
echo t('Showing <b>!pager_total_items</b> results', array('!pager_total_items' => $pager_total_items[0]));
and:
echo t('Showing !start-!end of <b>!pager_total_items</b> results', array('!start' => $start, '!end' => $end, '!pager_total_items' => $pager_total_items[0]));

That'll enter the strings into the translation system and allow them to be overridden if required.

This sort of thing is less critical when you're devising a theme for your own use, but still.

++Andy
Developing Drupal websites for Livelink New Media since 2008

janusman’s picture

Totally worked.

For the sake of clarity, here's the complete snippet:

global $pager_page_array, $pager_total_items, $pager_total;
$my_view = views_get_current_view();
$items_per_page = $my_view->pager['items_per_page'];
if ($pager_total[0] == 1) {
  echo t('Showing <b>!pager_total_items</b> results', 
    array('!pager_total_items' => $pager_total_items[0])
  ); 
} else {
  $start = 1 + ($pager_page_array[0] * $items_per_page);
  $end = (1 + $pager_page_array[0]) * $items_per_page;
  if ($end > $pager_total_items[0]) $end = $pager_total_items[0];
  echo t('Showing !start-!end of <b>!pager_total_items</b> results', 
    array('!start' => $start, '!end' => $end, '!pager_total_items' => $pager_total_items[0])
  );
}
pkiff’s picture

This cleaned up and merged version from janusman worked great from me on Drupal 6.15 with Views 6.x-2.8.

Finicky types might want to replace <b> with <strong> in keeping with more "semantic" XHTML code.

Also, FYI, I've added a note about this to the Working with Views - Tips and Tricks section where there is an item called: Add [Results x to y out of z] info to a view [drupal.org].

Thanks!

Phil.

brian_c’s picture

Getting totally offtopic here, but I've never really agreed with the whole "use strong instead of bold, because bold has no semantic meaning, only presentational".

Says who? Look up "bold" in any dictionary, I assure you it has a meaning beyond just the presentational. You can speak boldly. You can take a bold approach to something. "Strong" is not anymore semantically meaningful than "bold". They're equivalent.

Italic, on the other hand, is defined purely in terms of presentation, and is rightfully replaced by em.

jargylplath’s picture

The pieces of this debate that you're missing are two-fold:

1 - The definition of bold being referenced in the <b> tag is presentational.
2 - Strong is the secondary tag for emphasis. The idea is that you mark something that should be emphasized with <em>. If you need to mark something for emphasis but with a stronger emphasis you use <strong>.

Sorry for the incredibly delayed response. I just saw this while reading through the handbooks and I couldn't help myself.

brian_c’s picture

I understand how the W3C has (historically) defined it. What I am saying is that I disagree with defining <b> as purely presentational.

And in fact, HTML5 no longer does: http://dev.w3.org/html5/markup/b.html

jargylplath’s picture

Hahah. I can't believe the W3C is declaring a tag that is purely for presentational purposes. It goes against the entire reason a styleless, structure-based language was create in the first place!

*facepalm*

brian_c’s picture

It is no longer defined as purely presentational, that's the point. From the link above:

Although previous versions of HTML defined the b element only in presentational terms, the element has now been given the specific semantic purpose...

jargylplath’s picture

I know. That's why I'm disappointed in the W3C. For reversing their position. This is the tip of a slippery-slope that could undercut stylesheets, etc.

And for what purpose? What does this statement even mean:

a span of text offset from its surrounding content without conveying any extra emphasis or importance, and for which the conventional typographic presentation is bold text

To me, it seems like that means: when you purely just want to bold something. It doesn't mean what you were implying (to do something boldly, etc.), but it just means: if you're too lazy to wrap a span around something and give it a class. Which means that really they've put something in purely for presentational purposes and just defined it as being non-presentational.

If that's not what that statement means, how do you read it?

brian_c’s picture

I must admit I find their current wording confusing (without conveying extra emphasis or importance? OK... so what non-presentational meaning does it convey?). The first part of that sentence, doesn't seem to quite gel with the last part. Perhaps it will be refined, HTML5 is still a work-in-progress.

For me, the important bit is declaring it is no longer purely presentational. So personally speaking, anywhere something like <span class="important"> would make sense, I will consider <b> a valid alternative moving forward with HTML5. I won't consider it valid for simply indicating text that should be boldface.

HTML5 represents a fundamental shift for the W3C, from trying to enforce things (ie, the brittle super-strictness of XHTML 1.1), to recognizing and embracing current practices, and how browsers already work. I think it's a recognition of the simple fact that you can encourage and promote best practices, but you can't realistically enforce them without breaking large portions of the internet. The W3C's Design Principles document is enlightening in this regard, also see Jeremy Keith's excellent keynote from the last DrupalCon.

Ultimately, following best practices (ie, clean separation of content from presentation, the crux of the issue here, and something I think we're in complete agreement about) will still remain in the hands of actual developers.

jessebeach’s picture

<b> is semantic in this case. The total number of items isn't a highlighted term in terms of semantics; it's just highlighted in terms of presentation.

<b> catches the eye.

<strong> catches the eye and the brain.

whimsy’s picture

Thank you for this snippet. The code works great; however, I did encounter an issue when trying to use this with a view containing several page displays. The code would only render on the first page display. I'm not talking about a pager issue in the final views output. I have a view that contains five page displays (A, B, C, D, E...) The counter will only show on Page A of that view.

I'm not a coder, and it's beyond my current ability to tamper with the code, so I just split my view up into a separate view for each page. Worked like a charm. Just in case anyone else encounters this issue.

_vid’s picture

Hey Whimsy, I had the same problem.
I found out that you need a separate 'views_get_view()' call for each display and then you need to use $view->execute_display('display_name');

In this example I have two displays (page_1, attachment_1) in my view 'site_migration_list' and I'm using this code in the (php enabled) footer of my view's display:

<?php
$view = views_get_view('site_migration_list');
$view->execute_display('page_1');
$completedCount = count($view->result);
print('Finished: '.$completedCount.' | ');

$view2 = views_get_view('site_migration_list');
$view2->execute_display('attachment_1');
$toDoCount = count($view2->result);
print('To Do: '.$toDoCount.' | ');
print floor(($completedCount/$toDoCount)*100).'% Completed';
?>

Output: Finished: 10 | To Do: 454 | 2% Completed

It's not necessary to name the second views_get_view() var a different name. I had used $view2 in case I wanted pull other variables from that view, but I just tested it reusing $view and it works fine.
In fact, that means we can reuse that code!
So this is the version I'd recommend for 2 or more displays:

<?php
function recordCount($viewName,$displayName){
	$view = views_get_view($viewName);
	$view->execute_display($displayName);
	return count($view->result);
}
//get the first display's record count:	
$completedCount=recordCount('site_migration_list','page_1');
print 'Finished: '.$completedCount.' | ';

//get the 2nd display's record count:	
$toDoCount=recordCount('site_migration_list','attachment_1');
print 'To Do: '.$toDoCount.' | ';

//percentage
print floor(($completedCount/$toDoCount)*100).'% Completed';
?>

Same output: Finished: 10 | To Do: 454 | 2% Completed

_vid’s picture

If you wish to capture the record count of a view's display and include it in a block, then don't include any 'page' displays in your code. Executing page displays (even behind the scenes) will override the node's title with the view's page display title on every page the block is visible.

Details:
I'm executing a page and attachment display from with in a block display. It seemed to be working swimmingly; however, every page that the block appears on had its title replaced with the view's page display title. Even if that title was blank or <none>. Arg!!!
Testing:
Running the execute_display code directly from within a php block instead of a block display didn't help.
But ensuring none of the displays are pages does!
Solution:
So I replicated my page_1 display as a block (block_2) and updated my block_1 footer php code to use block_2 instead of page_1. Success! No page titles were overwritten!

Revised code:

<h2 class="title">Site Migration Page List</h2>
<?php
function recordCount($viewName,$displayName){
	$view = views_get_view($viewName);
	$view->execute_display($displayName);
	return count($view->result);
}
//get the first display's record count:	
$completedCount=recordCount('site_migration_list','block_2');
print 'Finished: '.$completedCount.'/';

//get the 2nd display's record count:	
$toDoCount=recordCount('site_migration_list','attachment_1');
print $toDoCount.'. ';

print floor(($completedCount/$toDoCount)*100).'% Completed.';
//also link to the page display containing the full report 
?> <a href="/admin/links"><span style="font-size:16px;">&raquo;</span>Full Report</a>
pkiff’s picture

In Views 3 with Drupal 6, the $items_per_page variable in the earlier post http://drupal.org/node/131031#comment-2507598 does not calculate correctly anymore if you are using the snippet above. To fix this, try replacing the third line:
$items_per_page = $my_view->pager['items_per_page'];
with:
$items_per_page = $my_view->query->pager->options['items_per_page'];

Worked for me with Drupal 6.26 and Views 6.x-3.0.

Alternatively, for those still running Drupal 6, the relatively new Views Record Count module looks promising. It eliminates the need for enabling PHP input, and the dev version was updated last week to work with Views 6.x-3.0. I haven't tried it as the Views 3-compatible version wasn't released yet when I was doing my testing.

Phil.

krueschi’s picture

Thanks a lot, Phil!
The upgrade from views 2 to views 3 had far more inflicts than expected. This was one of them and is now solved.

zeroyon’s picture

Worked great, cut and paste into footer, enable php

mpinch’s picture

This worked PERFECTLY! Thanks!!!

alienzed’s picture

Excellent information, may I ask where you found it? Views 2 documentation seems to be sorely lacking in any official sense. These global variables are so useful and yet take quite some searching to find...

kingandy’s picture

I got the details of $current_view by dumping it in a Drupal message:

global $current_view;
drupal_set_message('<pre>'. print_r($current_view, true) .'</pre>');

As to the rest of it - Views is actually making use of Drupal's core pager system here! I think I dug up most of the available pager variables by digging through the API docs. As noted above, that'll give you everything except the number of items per page. That doesn't look to have changed in 6.x - unfortunately.

FWIW, Matteo.borea has some ideas about Views 6.x-2.x code just up here.

++Andy
Developing Drupal websites for Livelink New Media since 2008

Stoob’s picture

Great solution. Searched for 1 hour for something like this. I just wanted to display the count(*)! This does it.

jusfeel’s picture

Thank you! It works great!

Eugene Fidelin’s picture

Thanx for great snippet. it also works in view's header.

--------------
www.bytek.biz
www.interesno.name

mooffie’s picture

Views 2.x doesn't have this global variable.

So it's better to do views_get_current_view() instead of $GLOBALS['current_view'].

(That function exists for Views 1.x as well.)

brian_c’s picture

I needed to do something like this, just pull the number of records for a view.

I actually need to do this in a Block, to summarize the results of multiple Views.

I got it working like this:

<?php

// load view object (has no results yet)
$view = views_get_view( 'name_of_view' );

// set arguments (if needed, otherwise omit this line)
$view->set_arguments( array( 1, 2, 3 ) );

// execute view query
$view->execute();

// results are now stored as an array in $view->result
$count = count( $view->result );

?>

I'm not sure if this works properly with a pager or not (none of the views I need this for use a pager), or if it just returns results for the current page. If you do have a pager, I think you should be able to use $view->total_rows.

adshill’s picture

Based on Brian's code, I used the following for a view without pager:

<?php

// load view object (has no results yet)
$view = views_get_current_view();

// execute view query
$view->execute();

// results are now stored as an array in $view->result
$count = count( $view->result );

print "Showing <b>$count</b> results";

?>

Just incase it's useful :)

field4000’s picture

It is possible to get the SUM of a column in a view using similar code?

brian_c’s picture

Just wanted to add some info for running a specific Display (other than default) from a View if you need to.

To do this, simply pass the ID of the Display in the execute() function.

HOWEVER! It can be a bit confusing at first figuring out what the ID of your Display actually is, because it doesn't really display this anywhere for you... the Display ID is *NOT* the same as the Name you assign to the Display in the Views UI.

The ID's are created automatically and are numbered based on the Display type. So ID's for Block Displays will be block_1, block_2, etc, and ID's for Page Displays will be page_1, page_2, etc. Once you know what you're looking for, it's easy to find these ID's; they are used all over the place in URLs related to that Display.

Because "page_2" isn't very descriptive, I tend to define constants in our project module which describe these better... so I wind up with something like:

<?php

define( 'MYPROJ_DISPLAY_FUBAR', 'page_2' );

// ...

$view = views_get_view( 'name_of_view' );
$view->set_arguments( array( 1, 2, 3 ) ); // optional
$view->execute( MYPROJ_DISPLAY_FUBAR );
$count = count( $view->result );

?>
mooffie’s picture

Doing count() will return the number of rows displayed on the page. If you want to find the number of *all* the rows, even those which were cut off the page, see my comment here.

joshg’s picture

Views total results. Views Custom Field
** Rownumber
Field containing rownumber (respects pagers).

http://drupal.org/project/views_customfield

bratsun’s picture

nobody pays attention to one little thing about total_rows counter but i would like to.

make sure you DON'T specify the number of items to display as unlimited. in that case pager has nothing to handle and therefore - nothing to display. i've been stuck with this issue for 2 days and finally my counters are alive again.

mugginsoft.net’s picture

Use hook_views_pre_render and inject row count element into attachment_after.

/*
 * views hook
 * 
 * hook_views_pre_render
 * 
 * called after view constructed but before it is rendered
 */
function MyModule_views_pre_render(&$view) {
 
  if ($view->pager['use_pager'] == 1) {

    // take a peek using developer module function
    //dpm($view);
    
    $total_rows = $view->total_rows;
    $items_per_page = $view->pager['items_per_page'];
    $page_count = ceil($total_rows/$items_per_page);
    $page_number = $view->pager['current_page'];  // 0 based
    
    $otag = "<span class='count'>";
    $ctag = "</span>";
    $suffix = ($total_rows == 1) ? "result" : "results";
    
    if ($page_count == 1) { // Number of pages == 1
      $content =  "Showing {$otag}{$total_rows}{$ctag} {$suffix}";
    }else if ($page_count > 1) {
      $start = $page_number * $items_per_page + 1;
      $end = $start + $items_per_page - 1;
      if ($end > $total_rows) $end = $total_rows;  // final page handling
      $content =  "Showing {$otag}{$start}{$ctag}-{$otag}{$end}{$ctag} of {$otag}{$total_rows}{$ctag} {$suffix}";
    }
    
    $view->attachment_after = "<div id='view-page-count'>{$content}</div>";
  }
}
druojajay’s picture

So I just wanted a conditional "more" link that would link to the second page of results instead of the first, and this is what I did:

<?php
$current_view = views_get_current_view();
if ($current_view->total_rows >= 20) {
print '<a href="/node/'.$current_view->args[0].'/posts?page=1">Read Older Posts &raquo;</a>';
} ?>

And it works. Sort of. The initial page is a views block embedded in a panel, and for some reason the above code only works when the panel settings are set to "use pager".

Panels or otherwise, can someone point me to a resource that explains when calls like views_get_current_view and the like are and are not available?

Thanks!

dru

kingandy’s picture

Well, judging by the API page I found on the internet, all it does is call a subsidiary function which stores the most recently "set" view in a static variable. So views_get_current_view will be available at any point in the pageload after the view is "set".

FWIW, I expect your code is breaking because the view object doesn't have a "total_rows" property when there's no pager. (I don't know for sure that it doesn't, but it's the only thing in your codeblock that would reasonably be affected by the pager setting.) Apparently there's a way to force Views to calculate the total rows, but I'm not sure how you'd inject that code - probably using one of these fancy new Views hooks that I'm hearing so much about.

Unfortunately the documentation for Views has always been more oriented towards front-end administration rather than theming or development (to the extent that the current help page simply says "Please put all documentation in the Advanced Help system"). However there are a couple of potentially useful references mentioned on the Project page - http://views.doc.logrus.com/ (developer-level) and http://views-help.doc.logrus.com/ (more of a how-to).

++Andy
Developing Drupal websites for Livelink New Media since 2008

alesuz’s picture

Excuse my ignorance, but when I put the php code in the footer of my view page it returns a text... What I should do?

brian_c’s picture

Not sure if I understand your problem, but if you mean you are seeing PHP code returned as your footer (instead of it running and returning a result) then you need to set the "Input Format" for the Footer to PHP. If you don't see this in the list of Input Formats, you need to enable the "PHP Filter" core module on the Modules page.

bkosborne’s picture

Hmm wow this is a pretty old thread

But I'm having an issue where I'd like to simply display the number of results in the view - and I'm not using a pager.

$current_view = views_get_current_view();
print "Total: ". $current_view->num_rows;

That doesn't seem to work in the footer of my view. Nothing is printed for the number...

WorldFallz’s picture

I don't see ->num_rows any where in this thread. ;-)

bkosborne’s picture

Yeah... its up top.... like the third comment

WorldFallz’s picture

ah ok, I missed that. In any case, you gotta read the whole thread. Views has changed over time which is reflected in the thread--

ATM, use the following:

$current_view = views_get_current_view();
print 'Total Items = ' . $current_view->total_rows;
bkosborne’s picture

Ah okay

I think my problem is a bit more complex now that I look at it.

The view that I'm trying to apply this to has a relationship and argument for the gallery itself.... I don't quite understand it... Its the Views Gallery module but I doubt anyone has used it here

WorldFallz’s picture

If you mean http://drupal.org/project/views_gallery, I use it all the time, lol. What exactly are you trying to do?

bkosborne’s picture

Okay well on the gallery page itself.... which is generated by the gallery_list view. So the gallery_list view will display all of the galleries by showing the latest picture from each of them with a link to the gallery. Below that I'd like to display the actual number of photos in the gallery as well.

The view that controls that is the "gallery" view with the "gallery image" display. In the footer of this display I have the code:

$current_view = views_get_current_view();
print 'Total Items = ' . $current_view->total_rows;

but nothing shows up for number of rows...

WorldFallz’s picture

Ah--ok. I'm not sure why it's not working (the code I posted works fine on my dev site), but even if it did, it would count the number of galleries, not the number of photos in the galleries.

I actually did this also, but I used a computed_field on the 'gallery' content type as follows:

$display = format_plural(db_result(db_query("SELECT COUNT(*) FROM {content_type_image} WHERE field_gallery_nid = '%d'", $node_field_item['value'])), '1 image', '@count images');

There might be better ways to do it, but I didn't want to waste too much time on it, and it worked fine.

bkosborne’s picture

Ah okay thanks! I'll try that out

faost’s picture


$current_view = views_get_current_view();
print count($current_view->result);

BeaPower’s picture

@faost Your way worked for d7 views using php custom field module, thanks!

dunklea’s picture

Thanks for this snippet. One quick request, though. How would I modify this to return results from the entire view argument? My view users a pager and this code is only counting the first page of results.

Thanks!
Andrew

dman’s picture

As I'm avoiding enabling php format, I (after lots of trial and error) found how to do it in my own module.

I filter to make sure I'm selecting one of my views ('staffsearch_internals') and add this to my module ('staffsearch_display')
so this is the desired outcome, thanks to HOOK_views_pre_render()

/**
 * HOOK_views_pre_render()
 * 
 * When rendering one of our own views, insert a count into the footer.
 */
function staffsearch_display_views_pre_render(&$view) {
  if ($view->name != 'staffsearch_internals') {
    return;
  }
  $view->style_plugin->display->handler->options['footer'] = count($view->result) . " items";
}
WorldFallz’s picture

NICE!

I've been meaning to figure this out for a while-- i try to avoid the php input format as well.

thanks for posting it!

rellimevad’s picture

To do this with views 3:

<?php
/**
 * HOOK_views_pre_render()
 * 
 * When rendering one of our own views, insert a count into the footer.
 */
function staffsearch_display_views_pre_render(&$view) {
  if ($view->name != 'staffsearch_internals') {
    return;
  }
  $view->attachment_after = $view->total_rows . " items";
}

There's attachment_before, as well, that will display the count in the header.

dman’s picture

Syntax is a little different

  $display_id = $view->plugin_name;
  $view->display[$display_id]->handler->options["header"]  = $view->total_rows  . " items!";
_vid’s picture

Someone asked me about using this in views custom field recently and it occurred to me that we might want to make sure the function doesn't exist before declaring it.
I think the code would look like this:

<?php
if(!function_exists('recordCount')){ //don't declare the function twice
  function recordCount($viewName,$displayName){
    $view = views_get_view($viewName);
    $view->execute_display($displayName);
    return count($view->result);
  }
}
//get the first display's record count:	
$completedCount=recordCount('site_migration_list','block_2');
print 'Finished: '.$completedCount.' || To do: ';

//get the 2nd display's record count:	
$toDoCount=recordCount('site_migration_list','attachment_1');
print $toDoCount.'. ';

print floor(($completedCount/($toDoCount+$completedCount))*100).'% Completed.';
?> <a href="/admin/links"><span style="font-size:16px;">&raquo;</span>Full Report</a>

In looking through the comments over the last few years, I see some notes about pagers. I haven't looked to see if this function accommodates that or not.

_vid’s picture

if(!function_exists('recordCount')){ //don't declare the function twice
  function recordCount($viewName,$displayName,$viewArgArray){
    $view = views_get_view($viewName);
    if (!$view || !$view->access($displayName)) {
      return;
    }
    $view->set_arguments( $viewArgArray );
    $view->execute_display($displayName);
    return count($view->result);
  }
}
//get a views display's record count:   
$viewsMeetingCommentCount = recordCount('meeting_minute_notes', 'attachment_2', array($data->nid));
print $viewsMeetingCommentCount;

This version of the record count function includes args. That's helpful when using this in a Customfield: PHP code.

I also added this snippet that may be pertinent if you only want to return the record count only if the user has access to that display:

if (!$view || !$view->access($displayName)) {
  return;
}
ankitchauhan’s picture

Hi

The code that is written above work but only for default display.

Here is a module named views record count for counting views query result. This module provides the functionality to customize the message display region (header/footer) and also work with overridden values in multiple display in a single view. But for that you have to enable the page in your views display.

allio_froggio’s picture

My apologies if someone has already mentioned this, but for us non- coders: you can also use Views to do this by using adding "Global: Result summary" (Shows result summary, for example the items per page) to your header/footer. It shows the record count by page as well as the total records for that view. (D7 with Views 7.x-3.3)

WorldFallz’s picture

nice-- i hadn't see that option. Note that it seem to be available only in the d7 version.

_vid’s picture

Excellent. Thanks for the info.

smartsystems160’s picture

@allio_froggio Can i achieve this using views 6.x? I have a view that correctly displays a user's "followers" and "following" twitter style (using user relationships, one way, can be reciprocated), but i want to display a block summary instead for each relationship (E.g 108 followers). Just the way twitter does it. Is it possible to achieve this with views? Or can someone assist with some code?

Alternatively, i would do with a code at the footer to display the summary of the total rows in a multiple page output... Thanks