开发者

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

开发者 https://www.devze.com 2023-01-21 00:50 出处:网络
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.

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 construct开发者_开发知识库ed 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.)


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;
    }
  }
}


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


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


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.


If anyone else comes across this question, you can use Views Summarize that adds a summarized table display. You just set the display and then choose how you want each column summarized. I haven't been able to get this to work with Views Data Export yet, but it works if you just want to see the data on the site.

0

精彩评论

暂无评论...
验证码 换一张
取 消