Adding a Google Charts plugin for views

Last modified: May 27, 2009 - 02:30

Here is some code that will let you add a Google Charts plugin for views. Couple of things I still need to work out:

a) sizing the chart - right now it is hardcoded
b) error handling

This code will help you display a chart assuming the first field is the x-axis and all the remaining fields are plotted on the y-axis. So the first field can be any field type, the remaining fields must be numeric fields..

<?php
function chartview_views_style_plugins() {
  $items['chartviewplugin'] = array(
    'name' => t('Chartview'),
    'theme' => 'chartview_view',
    'validate' => 'views_ui_plugin_validate_list',
    'needs_fields' => true,
    'weight' => 10,
  );
  return $items;
}

function theme_chartview_view($view, $nodes, $type) {
  $fields = _views_get_fields();

  $xaxis = array();
  $data = array();

  //need to flip the data array around..
  $ys = array();
  for ($i=1;$i<count($view->field);$i++) {
    $ys[] = array();
  }

  foreach ($nodes as $node) {
    $labels = array();
    $r = 0;
    foreach ($view->field as $field) {
      if (!$r) {
       $x = views_theme_field('views_handle_field', $field['queryname'], $fields, $field, $node, $view);
       $xaxis[] = strip_tags($x);
      }
      else {
       $y = views_theme_field('views_handle_field', $field['queryname'], $fields, $field, $node, $view);
       $ys[$r-1][] = $y !='' ?$y:-1;
       $labels[] = $field['label'];
      }
      $r++;
    }
  }

  foreach ($ys as $y) {
    $data[] = implode(',', $y);
  }

  $chart_size = "400x250";

  //plot it now..
  return '<img src="http://chart.apis.google.com/chart?chs='. $chart_size .'&amp;chd=t:' . implode('|', $data) .'&amp;cht=lc&amp;chxt=x,y&amp;chxl=0:|'. implode("|", $xaxis) .'|1:||'. $labels[0] .'" alt="'. views_get_title($view, $type) .'"/>';
}

Note

Make sure to check out the chart API module - http://drupal.org/project/chart It provides an API, so you do not need to form the google-API url yourself.

 
 

Drupal is a registered trademark of Dries Buytaert.