3

How can I display a view's count in a navigation item?

I have a view the displays a list of stories (a content type) and I have an item in a menu that links to that view. I need to display the number of items returned by that view next to the menu item that links to it on all pages of the site.

The solutions I've thought of so far have been:

  1. Add a block to the view and have that blocked displayed in a hidden area on all pages and then use the total_rows or num_rows property of the view's object. The disadvantage of this is that this view then runs on every page possibly causing performance issues.

  2. Add a block (or some other type) to the view that calculates the count and have that displayed by the menu item some how. But I haven't been able to figure out how to do this. I tried using the "Use aggregation" setting but I get a "broken/missing handler" error when using an "Aggregation type" other than "Group results together" in Sort or Filter criteria.

Any help with this would be much appreciated.

This is running on Drupal 7.7.

1 Answer 1

4

I know only how to get it with codding.
You can define in your module function, which gets total rows count from your view. And you can use drupal cache system for result, but actually you can use Views cache for it.
Something like that:

/**
 * Executes View to know rows count
 */
function testm_get_view_items_count($view_name, $display_id, $args) {
    $count = &drupal_static(__FUNCTION__);
    if(!isset($count)) {
        if($view = views_get_view($view_name)) {
            $view->set_arguments($args);
            $view->get_total_rows = true;
            $view->execute($display_id);
            if(isset($view->total_rows)) {
                $count = $view->total_rows;
            }
        }
    }
    return $count;
}

You can add cache_set/cache_get as Lulabots showed, but then you need to think about when to do flushing you cache.
You can use this function in THEMEORMODULE_preprocess_menu_link() function in Drupal 7. Here I showed example. This code works on D7.

1
  • I didn't actually end up using this. The responsibility for implementing this was moved to another developer and I'm not sure how he managed it. But this answer looks like it should work.
    – donut
    Jun 3, 2014 at 0:21

Your Answer

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

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