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.
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.
widgets
directory and add the ChartWidget
class:<?php namespace appwidgets; use yiiaseWidget; 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' . $this->height, 'chd' => 't:' . implode(',', $this->data), 'chds' => 'a', 'chl' => implode('|', $this->labels), 'chxt' => 'y', 'chxl' => '0:|0|' . max($this->data) ]); $url = $path . '?' . $query; return $this->render('chart', [ 'url' => $url, ]); } }
widgets/views/chart.php
view:<?php use yiihelpersHtml; /* @var $this yiiwebView */ /* @var $url string */ ?> <div class="chart"> <?= Html::img($url) ?> </div>
ChartController
controller:<?php namespace appcontrollers; use yiiaseController; class ChartController extends Controller { public function actionIndex() { return $this->render('index'); } }
views/chart/index.php
view:<?php use appwidgetsChartWidget; use yiihelpersHtml; /* @var $this yiiwebView */ $this->title = 'Chart'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="site-about"> <h1><?= Html::encode($this->title) ?></h1> <?= ChartWidget::widget([ 'title' => 'My Chart Diagram', 'data' => [ 100 - 32, 32, ], 'labels' => [ 'Big', 'Small', ], ]) ?> </div>
As in every other type of extension, we are creating some public properties we can configure when calling a widget using its widget
method. In this case, we are configuring the title, data set, and data labels.
The main method of a widget is run()
. In our widget, we are generating a URL and rendering the widget view, which uses the Google charting API for printing the <img>
tag.
18.217.220.114