Yii 2.0 Writing Widgets

Yii 2.0 Writing Widgets

In this post I want to teach you how to write a widget in Yii 2.0. Why do we need to add widgets to our projects? Well, sometime you want to have a specific block within different pages of your project.


In this post I want to teach you how to write a widget in Yii 2.0.

Why do we need to add widgets to our projects?

Well, sometime you want to have a specific block within different pages of your project. Or sometimes you need to have a block you can use in several projects. Instead of coding this block within every page or within every project, you can simply add that widget to your pages, or projects.

How can we write a widget?

Let’s get started on the process of writing widgets.

In your projects, there should be a folder named components. If you cannot find it, add it to your projects. In this folder add your php file. As an example we want a sidebar in our project. We add SideBar.php to this folder.

Now, in our file we should start like this:

<?php
    namespace app\components;


    use yii\base\Widget;

    class SideBar extends Widget
    {

        public function run()
        {
        }
    }

This is our widget. In our widget, we have a function called run(). When we use (call) our widget this function will be automatically called. You can also have a view. If you have a view, you must have a folder called views in you components folder and inside it you can add your view file.

You can do whatever you want, things that can be handled with controllers, inside run() function and in the end with the use of return $this->render() you can send the data to its view.

If you need to pass variables to your widget, add a public variable before run() function, and when calling your widget, you can set this variable.

How can we call our widget?

This is simple. Wherever you want to add your widget, simple add the following line:

<?php
    use app\components\SideBar;

    echo SideBar::widget();
?>

This will add your widget to the page. If you have variable(s) in your widget that you need to set, you can set it in the code above. For example, we have a public variable in our SideBar.php which is called $is_shown. Imagine you want to set it to true, this can be done in the following way:

<?php
    use app\components\SideBar;

    echo SideBar::widget(['is_shown'=>true]);
?>

You can have more variables and you need to send them in array!

Now you have learnt how to write a widgets in Yii 2.0