1 <?php
2 /**
3 * WhVisualizationChart widget class
4 * A simple implementation for for Google
5 *
6 * @author Antonio Ramirez <amigo.cobos@gmail.com>
7 * @copyright Copyright © 2amigos.us 2013-
8 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
9 * @package YiiWheels.widgets.google
10 */
11
12 class WhVisualizationChart extends CWidget
13 {
14 /**
15 * @var string $containerId the container Id to render the visualization to
16 */
17 public $containerId;
18
19 /**
20 * @var string $visualization the type of visualization -ie PieChart
21 * @see https://google-developers.appspot.com/chart/interactive/docs/gallery
22 */
23 public $visualization;
24
25 /**
26 * @var array $data the data to configure visualization
27 * @see https://google-developers.appspot.com/chart/interactive/docs/datatables_dataviews#arraytodatatable
28 */
29 public $data = array();
30
31 /**
32 * @var array $options additional configuration options
33 * @see https://google-developers.appspot.com/chart/interactive/docs/customizing_charts
34 */
35 public $options = array();
36
37 /**
38 * @var array $htmlOption the HTML tag attributes configuration
39 */
40 public $htmlOptions = array();
41
42 /**
43 * Widget's run method
44 */
45 public function run()
46 {
47 $id = $this->getId();
48 // if no container is set, it will create one
49 if ($this->containerId == null) {
50 $this->htmlOptions['id'] = 'div-chart'.$id;
51 $this->containerId = $this->htmlOptions['id'];
52 echo '<div ' . CHtml::renderAttributes($this->htmlOptions) . '></div>';
53 }
54 $this->registerClientScript();
55 }
56
57 /**
58 * Registers required scripts
59 */
60 public function registerClientScript()
61 {
62 $id = $this->getId();
63 $jsData = CJavaScript::jsonEncode($this->data);
64 $jsOptions = CJavaScript::jsonEncode($this->options);
65
66 $script = '
67 google.setOnLoadCallback(drawChart' . $id . ');
68 var ' . $id . '=null;
69 function drawChart' . $id . '() {
70 var data = google.visualization.arrayToDataTable(' . $jsData . ');
71
72 var options = ' . $jsOptions . ';
73
74 ' . $id . ' = new google.visualization.' . $this->visualization . '(document.getElementById("' . $this->containerId . '"));
75 ' . $id . '.draw(data, options);
76 }';
77
78 /** @var $cs CClientScript */
79 $cs = Yii::app()->getClientScript();
80 $cs->registerScriptFile('https://www.google.com/jsapi');
81 $cs->registerScript(
82 __CLASS__ . '#' . $id,
83 'google.load("visualization", "1", {packages:["corechart"]});',
84 CClientScript::POS_HEAD
85 );
86 $cs->registerScript($id, $script, CClientScript::POS_HEAD);
87 }
88 }