Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a summary row to a Drupal View?

I've built a view (Drupal 6.x, Views 2.x). I'd like to be able to add a summary row at the end of this view — total up several columns and include the totals in the summary row.

How can I do this? Is there some Views data-altering hook I can implement, to change the constructed data (before it gets themed)?

(Note that I can't use views_calc because some of the data in this view is coming from Views Relationships, which views_calc doesn't support at the time of writing.)

like image 768
smokris Avatar asked Oct 25 '10 02:10

smokris


3 Answers

To answer my own question a couple hours later... One way would be to implement hook_views_pre_render():

/**
 * Implementation of hook_views_pre_render().
 */
function mymodule_views_pre_render(&$view) {
  if ($view->name == 'myview') {
    // perform calculations on each row
    $pointsEarned = $pointsPossible = 0;
    foreach($view->result as $submission) {
      if (is_numeric($submission->node_data_field_pointsearned_field_pointsearned_value)) {
        $pointsEarned += $submission->node_data_field_pointsearned_field_pointsearned_value;
        $pointsPossible += $submission->node_node_data_field_pointspossible_field_pointspossible_value;
      }
    }


    // insert a 'total' row
    $row = new stdClass();
    $row->node_data_field_pointsearned_field_pointsearned_value = $pointsEarned;
    $row->node_node_data_field_pointspossible_field_pointspossible_value = $pointsPossible;
    $view->result[] = $row;

    if ($pointsPossible > 0) {
      // insert an 'average' row
      $row = new stdClass();
      $row->users_name = 'Average:';
      $row->node_data_field_pointsearned_field_pointsearned_value = round($pointsEarned/$pointsPossible * 100) . "%";
      $view->result[] = $row;
    }
  }
}
like image 61
smokris Avatar answered Nov 06 '22 20:11

smokris


Glancing around, it looks like Views Calc can do what you want.

like image 4
John Fiala Avatar answered Nov 06 '22 22:11

John Fiala


Views Calc has a lot of open bugs. View Summarize seems more stable.

like image 2
Simon Yost Avatar answered Nov 06 '22 20:11

Simon Yost