Drupal return number of results in a View
Solution 1
what you can do is to activate php for the views header/footer and add the following snippet to it:
<?php
$view = views_get_current_view();
print $view->total_rows;
?>
This will print the total number of rows.
If you need the result as a field, you could use the "Views custom field" module, add a php field and run the same snippet.
Regards
Mike
Solution 2
If you want to get the count outside the view you can use this
$view = views_get_view('MY_VIEW_NAME');
$view->set_display('MY_DISPLAY'); // like 'block_1'
$view->render();
print sizeof($view->result);
Note : Do not use this within a view. It will be an overhead. If you are using it within view check the other answers.
Solution 3
If using views_get_view
in Views 3, you can use this snippet:
$view = views_get_view('MY_VIEW');
$view->set_display('MY_DISPLAY');
// Execute first
$result = $view->preview('MY_DISPLAY');
// Output result only if rows > 0
if (count($view->result) > 0) {
print $result;
}
Solution 4
With Views 3 you may need to do
$view->get_total_rows = TRUE;
$total_items = $view->query->pager->get_total_items();
Solution 5
This works well for me and deals with the pager issues. Put this function in your custom module, rename / format as needed, and call it from your views-view--*view_name_goes_here*.tpl.php files.
function get_view_rowcount(){
$view = views_get_current_view();
$page_total = count($view->result);
if(isset($view->total_rows)){
return "<strong>Displaying " . $page_total . " of " . $view->total_rows . " total rows.</strong>";
} else {
return "<strong>Displaying " . $page_total . " of " . $page_total . " total rows.</strong>";
}
}
Related videos on Youtube
Linda
Updated on July 09, 2022Comments
-
Linda almost 2 years
I have a view in Drupal that filters my content. It brings back 7 rows. All I want to return is the number or results returned(7). Is this possible?
I tried using the View result counter but it returns a number for each results
1 2 3 4 5 6 7
I just need the 7 part.
So in SQL I would do a select count(*)
-
googletorp almost 14 yearspossible duplicate of Count number of results in a View
-
apaderno almost 5 yearsPossible duplicate of Count number of results in a View
-
-
Chris Cohen over 11 yearsReally not a very good idea to put PHP in the header and footer of a view! It's impossible to version this code, it's easy to forget it's there, it has no error checking on it, and more seriously, anyone with permission to edit the view has the permission to destroy your site by issuing a command that will delete the database.
-
Meetai.com over 11 yearsOverride the view's footer/header in code in a module or in a template: I think something like this: knackforge.com/blog/sabareesh/…
-
Felix Eve over 10 yearsCompletely agree with Chris - this is very bad practice, use Air's solution instead.
-
diamondsea about 6 yearsIf you featurize your views, you get versioning through your features.