The current project I'm working on has a lot of customization of Drupal Commerce and display of views. One of the customization I've done is while displaying views result, show total of two views results in one view i.e. there are two views viewA and viewB shown on page, which shares the output and so we need to show the sum of total results in viewA and viewB will be displayed in viewA header. Here's how I've achieved this with only few lines of code:
  • In viewA I've created "Global: Text Area" field with text as "We found @total_rows results.". @total_rows is used to replace with the total of both views result ahead.
  • Then, I've altered the viewA using hook_views_pre_render() hook where I can override the placeholders used in "Global: Text Area" in header i.e. @total_rows.
  • <?php
      function MODULE_NAME_views_pre_render(&$view) {
        if ($view->name == 'VIEW_A_NAME') {
          // We already get current views total in $view->total_rows.
          // So we only need to render viewB to get total of it.
          $view_b = views_get_view('VIEW_B_NAME');
          $view_b->set_display('VIEW_B_DISPLAY_NAME');
          $view_b->pre_execute();
          $view_b->execute('VIEW_B_DISPLAY_NAME');

          // Add total of both views.
          $rows = $view->total_rows + $view_b->total_rows;

          // You can update below hierarchy as per your view field.
          $view->display['VIEW_A_DISPLAY_NAME']->handler->view->header['result']->options['content'] =
            t($view->display['VIEW_A_DISPLAY_NAME']->handler->view->header['result']->options['content'], array(
              '@total_rows' => $rows, // Pass placeholder value to t() to replace.
            ));
    ?>
Submitted by ychaugule on