You are here

function charts_plugin_style_chart::query in Charts 6

Same name and namespace in other branches
  1. 7 views/charts_plugin_style_chart.inc \charts_plugin_style_chart::query()

Custom SQL query change.

File

views/charts_plugin_style_chart.inc, line 153
Contains the chart style plugin. @author Bruno Massa http://drupal.org/user/67164 @author Karen Stevenson http://drupal.org/user/45874

Class

charts_plugin_style_chart
Style plugin to render view as a chart.

Code

function query() {
  parent::query();

  // Clear the fields out, we'll replace them with calculated values.
  $this->view->query
    ->clear_fields();

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

  // Add the grouping information to the query.
  // Field setting of array('aggregate' => TRUE) tells Views not to force
  // another aggregation in for this field.
  foreach ($this->view->field as $field) {
    $query_field = substr($field->field, 0, 3) == 'cid' ? $field->definition['calc'] : $field->table . '.' . $field->field;
    $query_alias = $field->field_alias;

    // Add the aggregation.
    if ($field->field == $this->options['aggregation_field']) {
      $this->view->query
        ->add_orderby(NULL, NULL, 'asc', $query_alias);
      $this->view->query
        ->add_groupby($query_field);
      if (substr($field->field, 0, 3) == 'cid') {
        $this->view->query
          ->add_field(NULL, $query_field, $field->field, array(
          'aggregate' => TRUE,
        ));
      }
      else {
        $this->view->query
          ->add_field($field->table, $field->field, NULL, array(
          'aggregate' => TRUE,
        ));
      }
    }

    // Add computed values.
    if (in_array($field->field, $this
      ->calc_fields())) {
      $sql = "ROUND(" . $this->options['calc'] . "({$query_field}), " . $this->options['precision'] . ")";
      $this->view->query
        ->add_field(NULL, $sql, $field->field, array(
        'aggregate' => TRUE,
      ));

      // TODO This part is not relationship-safe, needs additional work
      // to join in the right table if the computation is done
      // on a field that comes from a relationship.
      // Make sure the table with the right alias name is available
      // (it might have been dropped during Views optimizations.)
      $this->view->query
        ->add_table($field->table);
    }
  }
}