In the work of the YII2 framework, before the widgets of Yii is not very understanding, there is no use. When I recently looked at YII2 's English guide, I finally figured out what was going on.
As a simple example, if you are doing background development, most pages need an optional list (<select>), then we can make it into a form widget.
See the following code specifically:
<?php/** * created by phpstorm. * user: administrator * date: 2017/2/14 * time: 18:01 */namespace common\widgets;use common\service\ gameservice;use yii\base\widget;use yii\helpers\arrayhelper;class gamewidget extends widget{ private $list; private $html; public function init () { parent::init (); $this->list = Gameservice::gamelist ([' id ', ' gamename '); $array = arrayhelper::toarray ($this->list); $this->html = ' <select data-am-selected= ' {btnsize: "SM"} "> '; foreach ($array as $key => $val) { $this->html .= ' <option value= '. $val [' id ']. ' " > '. $val [' gamename ']. ' </option> '; } $this->html.= ' </select> '; } public function run () { return $this->html ; }}
Create a new class, and inherit from Yii\base\widget. Override the Init () and run () methods. Init writes its own logic, and the run returns content that needs to be displayed on the page.
Here's how to look at the PHP template page
<?phpuse common\widgets\gamewidget;? ><?php Echo gamewidget::widget ()?>
Introduce your own widgets, and then call the widget () method.
Result diagram
650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>
650) this.width=650; "Src=" https://s1.51cto.com/wyfs02/M00/8D/A4/wKioL1ilDTWi9jIWAAAGVaOCV2E484.png-wh_500x0-wm_ 3-wmp_4-s_3839671735.png "style=" Float:none; "title=" QQ picture 20170216102223.png "alt=" Wkiol1ildtwi9jiwaaagvaocv2e484.png-wh_50 "/>
650) this.width=650; "Src=" https://s1.51cto.com/wyfs02/M02/8D/A4/wKioL1ilDTWRpSx7AAAXQ8IDaAU005.png-wh_500x0-wm_ 3-wmp_4-s_1091870544.png "style=" Float:none; "title=" QQ picture 20170216102145.png "alt=" Wkiol1ildtwrpsx7aaaxq8idaau005.png-wh_50 "/>
Later on in other pages if you need this part, you can only call. No more code to write.
This article is from the PHP learning blog, so be sure to keep this source http://xtceetg.blog.51cto.com/5086648/1898339
YII2.0 Form Widget