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 new yii2-app-basic
application using the composer as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html.
How to do it…
Create the
widgets
directory and add theChartWidget
class:<?php namespace app\widgets; use yii\base\Widget; class ChartWidget extends Widget { public $title; public $width = 300; public $height = 200; public $data = []; public $labels = []; public function run() { $path = 'http://chart.apis.google.com/chart'; $query = http_build_query([ 'chtt' => $this->title, 'cht' => 'pc', 'chs' => $this->width . 'x...