Creating a widget
A widget is a reusable part of a view that not only renders some data but also does it according to some logic. It can even get data from models and use its own views, so it is like a reduced reusable version of a module.
Let's create a widget that will draw a pie chart using Google APIs.
Getting ready
Create a fresh Yii application using yiic webapp.
How to do it...
Create
protected/extensions/chart/EChartWidget.php:<?php class EChartWidget extends CWidget { public $title; public $data=array(); public $labels=array(); public function run() { echo "<img src=\"http://chart.apis.google.com/chart?chtt=".urlencode ($this->title)."&cht=pc&chs=300x150&chd=". $this->encodeData($this->data)."&chl=".implode ('|', $this->labels)."\">"; } protected function encodeData($data) { $maxValue=max($data); $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx yz0123456789'; $chartData...