You are here

function views_calc_table::add_aggregation_fields in Views Calc 7

Query grand total.

1 call to views_calc_table::add_aggregation_fields()
views_calc_table::execute_summary_view in ./views_calc_table.inc

File

./views_calc_table.inc, line 208
Copied from the table style plugin.

Class

views_calc_table
Style plugin to render each item as a row in a table.

Code

function add_aggregation_fields(&$view) {

  // Create summary rows.
  // Empty out any fields that have been added to the query,
  // we don't need them for the summary totals.
  $view->query->fields = array();

  // Clear out any sorting and grouping, it can create unexpected results
  // when Views adds aggregation values for the sorts.
  $view->query->orderby = array();
  $view->query->groupby = array();

  // See if this view has any calculations.
  $has_calcs = TRUE;
  $calc_fields = $view->views_calc_fields;
  foreach ($calc_fields as $calc => $fields) {
    foreach ($view->field as $field) {

      // Is this a field or a property?
      if (!empty($field->field_info)) {
        $query_field = substr($field->field, 0, 3) == 'cid' ? $field->definition['calc'] : $field->table . '.' . $field->real_field;
      }
      else {
        $query_field = substr($field->field, 0, 3) == 'cid' ? $field->definition['calc'] : $field->table_alias . '.' . $field->real_field;
      }
      if (isset($field->aliases['entity_type'])) {
        $query_alias = $field->aliases['entity_type'];
      }
      else {
        $query_alias = $field->field_alias;
      }

      // Bail if we have a broken handler.
      if ($query_alias == 'unknown') {
        continue;
      }
      $view->query
        ->add_table($field->table, $field->relationship, NULL, $field->table);

      // aggregation functions
      $ext_alias = views_calc_shorten($calc . '__' . $query_alias);
      if (in_array($field->options['id'], $fields)) {

        // Calculated fields.
        $view->query
          ->add_field(NULL, $calc . '(' . $query_field . ')', $ext_alias);
        $has_calcs = TRUE;
      }
    }
  }

  // TODO This won't work right with relationships, need a fix here.
  // Limit to specific primary ids. This is for subtotals.
  if (!empty($view->views_calc_ids)) {

    //$view->query->add_where(NULL, $view->base_table . "." . $view->base_field . " IN (%s)", implode(',', $view->views_calc_ids));
    $view->query
      ->add_where(NULL, $view->base_table . "." . $view->base_field, $view->views_calc_ids);
  }

  // TODO We may need to ask which field to group by.
  // Some databases are going to complain if we don't have a groupby field with using aggregation.
  if ($has_calcs) {
    $this->view->query
      ->add_groupby($this->view->base_table . '.' . $this->view->base_field);
  }
}