You are here

class charts_plugin_style_chart in Charts 7

Same name and namespace in other branches
  1. 6 views/charts_plugin_style_chart.inc \charts_plugin_style_chart
  2. 7.2 views/charts_plugin_style_chart.inc \charts_plugin_style_chart

Style plugin to render view as a chart.

Hierarchy

Expanded class hierarchy of charts_plugin_style_chart

1 string reference to 'charts_plugin_style_chart'
charts_views_plugins in views/charts.views.inc
Implementation of hook_views_plugins().

File

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

View source
class charts_plugin_style_chart extends views_plugin_style {

  /**
   * Set default options.
   */
  function options(&$options) {

    // Get the default chart values
    module_load_include('inc', 'charts');
    $options['charts'] = _charts_settings();

    // (yet) Non default chartssettings
    $form['show_legend'] = TRUE;
    $form['show_sums'] = TRUE;
    $options['aggregation_field'] = '';
    $options['calc_fields'] = array();
    $options['calc'] = 'COUNT';
    $options['precision'] = 2;
  }

  /**
   * Generate a form for setting options.
   */
  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);

    // Add the Chart Settings form
    module_load_include('admin.inc', 'charts');

    // Get chart settings from options form.
    _charts_settings_form($form['charts'], $this->options['charts']);
    $form['show_legend'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show legend'),
      '#default_value' => $this->options['show_legend'],
      '#description' => t('Display legend next to the chart.'),
    );
    $form['show_sums'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show individual sums'),
      '#default_value' => TRUE,
      '#description' => t('Display the sum for each column in the chart legends'),
    );

    // Views Calc related fields
    $form['aggregation_field'] = array(
      '#type' => 'select',
      '#title' => t('Legend field'),
      '#options' => $this
        ->aggregated_field_options(),
      '#default_value' => $this->options['aggregation_field'],
      '#description' => t('Select a field to aggreagate the results on.'),
    );

    // TODO Charts module cannot currently handle more than one series,
    // update Multiple to TRUE if that changes.
    $form['calc_fields'] = array(
      '#type' => 'select',
      '#title' => t('Operation field'),
      '#options' => $this
        ->aggregated_field_options(),
      '#default_value' => $this
        ->calc_fields(),
      '#multiple' => FALSE,
      '#description' => t('Select field to perform computations on.'),
    );
    $form['calc'] = array(
      '#type' => 'select',
      '#title' => t('Operation'),
      '#options' => $this
        ->calc_options(),
      '#default_value' => $this->options['calc'],
    );
    $form['precision'] = array(
      '#type' => 'select',
      '#title' => t('Precision'),
      '#options' => range(0, 4),
      '#default_value' => $this->options['precision'],
      '#description' => t('Decimal points to use in computed values.'),
    );
  }

  /**
   * Generate a form for setting options.
   */
  function options_submit(&$form, &$form_state) {
    $chart =& $form_state['values']['style_options']['charts'];
    foreach (element_children($chart) as $index) {
      $chart['#' . $index] = $chart[$index];
      unset($chart[$index]);
    }
  }

  /**
   * Views Calc operation.
   */
  function calc_options() {
    return array(
      '' => t('None'),
      'SUM' => t('Sum'),
      'COUNT' => t('Count'),
      'AVG' => t('Average'),
      'MIN' => t('Minimum'),
      'MAX' => t('Maximum'),
    );
  }

  /**
   * Create an options array of available fields from this view.
   */
  function aggregated_field_options() {
    $field_names = array();
    $handlers = $this->display->handler
      ->get_handlers('field');
    foreach ($handlers as $field => $handler) {
      if ($label = $handler
        ->label()) {
        $field_names[$field] = $label;
      }
      else {
        $field_names[$field] = $handler
          ->ui_name();
      }
    }
    return $field_names;
  }

  /**
   * Make sure calc_fields is always an array, even when not multiple.
   */
  function calc_fields() {
    $calc_fields = (array) $this->options['calc_fields'];
    return array_values($calc_fields);
  }

  /**
   * Define and display a chart from the grouped values.
   */
  function render() {

    // Get chart settings from options form.
    $chart = $this->options['charts'];

    // Get values from rows.
    foreach ($this
      ->calc_fields() as $calc) {
      foreach ($this->view->result as $row) {
        foreach ($this->view->field as $key => $field) {
          if ($key == $this->options['aggregation_field']) {
            $legend_field = array_key_exists($calc, $this->view->field) ? $this->view->field[$calc] : NULL;
            $legend = !empty($legend_field->options['label']) ? $legend_field->options['label'] : NULL;
            if ($this->options['show_legend']) {
              $data[$calc]['#legend'] = $legend;
            }
            $value['#label'] = strip_tags(theme_views_view_field($this->view, $this->view->field[$key], $row));
            if ($this->options['show_sums']) {
              $value['#label'] .= ' (' . $row->{$calc} . ')';
            }
            $value['#value'] = $row->{$calc};
            $chart[$calc][] = $value;
          }
        }
      }
    }

    // Print the chart.
    return charts_chart($chart);
  }

  /**
   * Custom SQL query change.
   */
  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);
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
charts_plugin_style_chart::aggregated_field_options function Create an options array of available fields from this view.
charts_plugin_style_chart::calc_fields function Make sure calc_fields is always an array, even when not multiple.
charts_plugin_style_chart::calc_options function Views Calc operation.
charts_plugin_style_chart::options function Set default options. Overrides views_object::options
charts_plugin_style_chart::options_form function Generate a form for setting options. Overrides views_plugin_style::options_form
charts_plugin_style_chart::options_submit function Generate a form for setting options. Overrides views_plugin::options_submit
charts_plugin_style_chart::query function Custom SQL query change. Overrides views_plugin_style::query
charts_plugin_style_chart::render function Define and display a chart from the grouped values. Overrides views_plugin_style::render
views_object::$definition public property Handler's definition.
views_object::$options public property Except for displays, options for the object will be held here. 1
views_object::altered_option_definition function Collect this handler's option definition and alter them, ready for use.
views_object::construct public function Views handlers use a special construct function. 4
views_object::export_option public function 1
views_object::export_options public function
views_object::export_option_always public function Always exports the option, regardless of the default value.
views_object::set_default_options public function Set default options.
views_object::set_definition public function Let the handler know what its full definition is.
views_object::unpack_options public function Unpack options over our existing defaults, drilling down into arrays so that defaults don't get totally blown away.
views_object::unpack_translatable public function Unpack a single option definition.
views_object::unpack_translatables public function Unpacks each handler to store translatable texts.
views_object::_set_option_defaults public function
views_plugin::$display public property The current used views display.
views_plugin::$plugin_name public property The plugin name of this plugin, for example table or full.
views_plugin::$plugin_type public property The plugin type of this plugin, for example style or query.
views_plugin::$view public property The top object of a view. Overrides views_object::$view 1
views_plugin::additional_theme_functions public function Provide a list of additional theme functions for the theme info page.
views_plugin::plugin_title public function Return the human readable name of the display.
views_plugin::summary_title public function Returns the summary of the settings in the display. 8
views_plugin::theme_functions public function Provide a full list of possible theme templates used by this style.
views_plugin_style::$row_plugin public property The row plugin, if it's initialized and the style itself supports it.
views_plugin_style::$row_tokens public property Store all available tokens row rows.
views_plugin_style::build_sort public function Called by the view builder to see if this style handler wants to interfere with the sorts. If so it should build; if it returns any non-TRUE value, normal sorting will NOT be added to the query. 1
views_plugin_style::build_sort_post public function Called by the view builder to let the style build a second set of sorts that will come after any other sorts in the view. 1
views_plugin_style::destroy public function Destructor. Overrides views_object::destroy
views_plugin_style::even_empty public function Should the output of the style plugin be rendered even if it's empty. 1
views_plugin_style::get_field public function Get a rendered field.
views_plugin_style::get_field_value public function Get the raw field value.
views_plugin_style::get_row_class public function Return the token replaced row class for the specified row.
views_plugin_style::init public function Initialize a style plugin.
views_plugin_style::options_validate public function Validate the options form. Overrides views_plugin::options_validate
views_plugin_style::option_definition public function Information about options for all kinds of purposes will be held here. Overrides views_object::option_definition 8
views_plugin_style::pre_render public function Allow the style to do stuff before each row is rendered.
views_plugin_style::render_fields public function Render all of the fields for a given style and store them on the object.
views_plugin_style::render_grouping public function Group records as needed for rendering.
views_plugin_style::render_grouping_sets public function Render the grouping sets.
views_plugin_style::tokenize_value public function Take a value and apply token replacement logic to it.
views_plugin_style::uses_fields public function Return TRUE if this style also uses fields.
views_plugin_style::uses_row_class public function Return TRUE if this style also uses a row plugin.
views_plugin_style::uses_row_plugin public function Return TRUE if this style also uses a row plugin.
views_plugin_style::uses_tokens public function Return TRUE if this style uses tokens.
views_plugin_style::validate public function Validate that the plugin is correct and can be saved. Overrides views_plugin::validate