Yii2 Widgets & Using Built-in Widgets

Introduction

Yii2 provides a powerful and flexible widget system that allows developers to create reusable UI components. Widgets are a type of reusable component that encapsulates a specific functionality and can be easily included in views. Yii2 comes with a set of built-in widgets, but you can also create custom widgets as needed.


Understanding Widgets in Yii2

Widgets in Yii2 are small, reusable components that help in rendering content dynamically. They are implemented as PHP classes extending yii\base\Widget. When a widget is used, Yii2 instantiates it, runs its logic, and outputs the result.

Widgets in Yii2 follow this structure:

  1. Init: Prepares the widget before it gets executed.
  2. Run: Executes the widget and returns the output.
  3. View Rendering: Widgets usually render a view file.

Using Built-in Widgets

Yii2 provides several built-in widgets, including:

  • ActiveForm - yii\widgets\ActiveForm
  • ListView - yii\widgets\ListView
  • DetailView - yii\widgets\DetailView
  • GridView - yii\grid\GridView
  • Menu - yii\widgets\Menu
  • Breadcrumbs - yii\widgets\Breadcrumbs

Example of a Built-in Widget

Using ActiveForm Widget
use yii\widgets\ActiveForm;
use yii\helpers\Html;

$form = ActiveForm::begin();
    echo $form->field($model, 'username');
    echo $form->field($model, 'email');
    echo Html::submitButton('Submit', ['class' => 'btn btn-primary']);
ActiveForm::end();

This widget simplifies form creation and validation using Yii2's model system.


Creating a Custom Widget

Sometimes, built-in widgets do not fulfill all requirements, and custom widgets are needed. Below is an example of a custom widget.

Steps to Create a Custom Widget

  1. Create a new PHP class extending yii\base\Widget.
  2. Implement the run() method.
  3. Optionally, include a separate view file for the widget output.

Example of a Custom Widget

Step 1: Create a Widget Class
namespace app\components;

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

class HelloWidget extends Widget
{
    public $message;

    public function init()
    {
        parent::init();
        if ($this->message === null) {
            $this->message = 'Hello, World!';
        }
    }

    public function run()
    {
        return Html::tag('h1', Html::encode($this->message), ['class' => 'hello-widget']);
    }
}
Step 2: Use the Widget in a View
use app\components\HelloWidget;

echo HelloWidget::widget(['message' => 'Welcome to Yii2!']);

This will output:

<h1 class="hello-widget">Welcome to Yii2!</h1>

Real-World Example: Profile Menu Widget

Below is a real-world example of a Profile Menu Widget, commonly used in dashboards to show user information and options.

Widget Class (ProfileMenu.php)

namespace fdcore\widgets;

use Yii;
use yii\base\Widget;

class ProfileMenu extends Widget
{
    public $active_url;
    public $display = true;
    public $show_changepassword = true;
    public $show_darkmode_icon = false;

    public function run()
    {
        if (!Yii::$app->user->identity) {
            $this->display = false;
        }

        if ($this->display) {
            return $this->render('profilemenu', [
                'show_changepassword' => $this->show_changepassword,
                'show_darkmode_icon' => $this->show_darkmode_icon,
            ]);
        }
    }
}

Widget View File (profilemenu.php)

<?php if ($show_darkmode_icon) { ?>
<li class="dropdown nav-item">
    <a class="nav-link theme-layout layout-setting">
        <span class="dark-layout">🌙</span>
        <span class="light-layout">☀️</span>
    </a>
</li>
<?php } ?>

<li class="dropdown main-profile-menu">
    <a class="nav-link profile-user" href="#" data-bs-toggle="dropdown">
        <img src="/images/profile.jpg" alt="">
    </a>
    <div class="dropdown-menu">
        <div class="menu-header-content p-3 border-bottom">
            <div class="d-flex">
                <div class="main-img-user">
                    <img src="/images/profile.jpg" alt="">
                </div>
                <div class="ms-3 my-auto">
                    <h6 class="tx-15"> <?= Yii::$app->user->identity->fullname ?? '' ?> </h6>
                    <span class="tx-12"> <?= Yii::$app->user->identity->username ?? '' ?> </span>
                </div>
            </div>
        </div>
        <?php if ($show_changepassword) { ?>
            <a class="dropdown-item popupButton" value="/site/changepassword"><i class="fa fa-key"></i> Change Password</a>
        <?php } ?>
        <a class="dropdown-item" href="/site/logout" data-method="post">
            <i class="far fa-arrow-alt-circle-left"></i> Sign Out
        </a>
    </div>
</li>

Using the Profile Menu Widget in Views

echo ProfileMenu::widget(['show_changepassword' => true, 'show_darkmode_icon' => true]);

This widget dynamically displays a profile menu based on user authentication and provides options to log out or change the password.


Conclusion

Yii2 widgets are an essential feature for building reusable UI components. This tutorial covered:

  • Understanding Yii2 widgets
  • Using built-in widgets
  • Creating custom widgets
  • A real-world example of a profile menu widget

By mastering Yii2 widgets, you can create modular and maintainable web applications.