views:

41

answers:

3

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.)

A: 

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;
    }
  }
}
smokris
+1  A: 

Personally, I would handle this in the view templates. Create a views-view.tpl.php for your view, and then edit it calculate and print out the summary.

Another option is to create another display for the same view, and then create a views-view-unformatted.tpl.php and calculate and print out the summary w/o doing a print $row; to avoid calling the fields template. The add use view display where needed.

MPD
A: 

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

John Fiala

related questions