Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By ethansen on
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
...
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.
Code that worked for me
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.)
Thanks. That worked great.
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.
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.
Pages beyond 1
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.
--Andy
Developing Drupal websites for Livelink New Media
++Andy
Developing Drupal websites for Livelink New Media since 2008
Andy, this is a great
Andy, this is a great snippet which works out-of-the-box! Thank you very much.
Works perfectly
Thanks kingandy, this really works great!
-------------------------------
My Drupal site which I love to pieces: Download a Book.
-------------------------------
My Drupal site: Download a Book.
Would this be expected to work for the newest Views2 version?
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
I'm afraid I know nothing
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 forglobal $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:
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
Thanks to Andy and Moofie.
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.
For Views 6.x-2.6
Code of kingandy adapted. Same behaviour. For contextual use (e.g.: in footer or header).
Looking at this now I
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
Awesome, thanks!
Totally worked.
For the sake of clarity, here's the complete snippet:
This cleaned up and merged
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.
In defense of the bold tag [OT]
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.
In defense of the strong tag [More OT]
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.
Long live bold! ;) [OT]
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
*groan*
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*
It is no longer defined as
It is no longer defined as purely presentational, that's the point. From the link above:
That's why I'm disappointed.
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:
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?
I must admit I find their
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.
<b> is semantic in this case.
<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.
View containing multiple page displays
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.
Record count for multiple displays
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:
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:
Same output: Finished: 10 | To Do: 454 | 2% Completed
Watch out for page title overrides.
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:
Edit for PHP insert method for Drupal 6 with Views 3
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.
Drupal 6 with Views 3
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.
Excellent worked out of the box
Worked great, cut and paste into footer, enable php
You folks totally Rock!!
This worked PERFECTLY! Thanks!!!
Excellent information, may I
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...
I got the details of
I got the details of $current_view by dumping it in a Drupal message:
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
kingandy you rock
Great solution. Searched for 1 hour for something like this. I just wanted to display the count(*)! This does it.
Works Great!
Thank you! It works great!
Thanx for great snippet. it
Thanx for great snippet. it also works in view's header.
--------------
www.bytek.biz
www.interesno.name
...
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.)
Got it working in Drupal 6 - With no pager too
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:
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.
Based on Brian's code, I
Based on Brian's code, I used the following for a view without pager:
Just incase it's useful :)
Is it possible to get the SUM?
It is possible to get the SUM of a column in a view using similar code?
For specific Displays
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:
...
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.
Views Custom Field
Views total results. Views Custom Field
** Rownumber
Field containing rownumber (respects pagers).
http://drupal.org/project/views_customfield
nobody pays attention to one
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.
Drupal 6 pager row count
Use hook_views_pre_render and inject row count element into attachment_after.
Logic for availability?
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:
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
Some links
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
Basic doubt
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?
Not sure if I understand your
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.
Hmm wow this is a pretty old
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.
That doesn't seem to work in the footer of my view. Nothing is printed for the number...
_
I don't see
->num_rows
any where in this thread. ;-)Yeah... its up top.... like
Yeah... its up top.... like the third comment
_
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:
Ah okay I think my problem is
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
_
If you mean http://drupal.org/project/views_gallery, I use it all the time, lol. What exactly are you trying to do?
Okay well on the gallery page
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:
but nothing shows up for number of rows...
_
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:
There might be better ways to do it, but I didn't want to waste too much time on it, and it worked fine.
Ah okay thanks! I'll try that
Ah okay thanks! I'll try that out
my way
@faost Your way worked for
@faost Your way worked for d7 views using php custom field module, thanks!
Thanks for this snippet. One
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
Doing it without a php snippet - in a local module instead
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()
.dan. is the New Zealand Drupal Developer working on Government Web Standards
_
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!
Views 3
To do this with views 3:
There's attachment_before, as well, that will display the count in the header.
Views2 View 2 (6.x-2.12 anyway)
Syntax is a little different
.dan. is the New Zealand Drupal Developer working on Government Web Standards
Just a follow up to anyone using the function recordCount().
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:
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.
Adding args and access control
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:
views record count
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.
You might not need PHP to do this...
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)
_
nice-- i hadn't see that option. Note that it seem to be available only in the d7 version.
Excellent. Thanks for the
Excellent. Thanks for the info.
can i achieve this results summary in views 6.x?
@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