Monday, 24 October 2016

Create your first widget in Yii2

In this tutorial i will show you how you can create own custom widget in Yii2.The main advantage of Widget is you can write once and reuse it wherever you need it in your view. Widgets are reusable blocks and they are used in your views. Create a custom widget we must extend the base widget yii\base\Widget and we have to override the init() or run() methods of base widget.

Yii2 Widget


Step 1: Create a folder named components or changed name in your project folder.

Step 2: Create a file with desired widget name inside components folder and paste the below code. Example – HelloWidget.php


<?php

namespace app\components;

use yii\base\Widget;
use yii\helpers\Html;

class Hellowidget extends Widget
{

    public $msg;

    public function init()
    {
        
        parent::init();

        if ($this->msg === null) {
            $this->msg = 'Welcome Here';
        } else {
            $this->msg = 'Welcome ' . $this->msg;
        }
    }

    public function run()
    {
        // you can load & return the view or you can return the output variable
        return $this->render('my-widge', ['message' => $this->msg]);
    }
}

In HelloWidget is a class and we can access the widget like 'app\components\HelloWidget'.

Step 3: Create a view and put the content into it.

Step 4: Everything is done.you can call now widget.


<?php echo \app\components\HelloWidget::widget() ?>

I hope you like the post. please share and comment.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts