- Yii2 Framework
-
Introduction & Setup
- Introduction to Yii2 Framework
- Installing Yii2 (Basic & Advanced Templates)
- Understanding Yii2 Directory Structure
- Yii2 Configuration Basics
- Routing & Pretty URLs in Yii2
-
Yii2 Core Concepts
- Yii2 Application Bootstrapping & Lifecycle
- Understanding Yii2 Request & Response Handling
- Working with Yii2 Components & Helpers
- Yii2 Widgets & Using Built-in Widgets
- Yii2 Helpers & Utility Classes
-
Models & Database Operations
- Yii2 Models, Active Record & Database Connections
- CRUD Operations in Yii2
- Yii2 Query Builder & DAO (Direct SQL Queries)
- Handling Relationships in Yii2 Active Record
- Yii2 Migrations & Seeding
-
Views, Layouts & Themes
- Yii2 Views & Layouts
- Yii2 Asset Bundles & Asset Management
- Integrating Bootstrap in Yii2
- Yii2 Theme Integration
- Yii2 Custom Widgets & Reusable Components
-
Forms, Validation & Data Presentation
- Yii2 Forms & Validation
- Using Yii2 GridView & ListView Widgets
- Yii2 Pagination & Sorting
- Yii2 File Uploads
-
Security & User Management
- User Authentication in Yii2
- Role-Based Access Control (RBAC) in Yii2
- Yii2 Security Features
-
Console Commands & Advanced Features
- Yii2 Console Commands
- Yii2 Events & Behaviors
- Yii2 RESTful API Development
- Consuming Third-Party APIs in Yii2
- Yii2 Background Jobs & Queue System
-
Performance Optimization & Caching
- Yii2 Caching Techniques
- Yii2 Performance Optimization
- Debugging & Logging in Yii2
-
Deployment & Best Practices
- Deploying Yii2 Applications
- Yii2 Best Practices & Large-Scale Application Structure
- Yii2 Multilingual & Localization Support
- Yii2 Module Development
- Integrating Yii2 with Frontend Frameworks (Angular/Vue/React)
-
Special Topics
- Dependency Injection (DI) in Yii2
Yii2 Widgets & Using Built-in Widgets
Add to BookmarkIntroduction
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:
- Init: Prepares the widget before it gets executed.
- Run: Executes the widget and returns the output.
- 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
- Create a new PHP class extending
yii\base\Widget
. - Implement the
run()
method. - 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.
Prepare for Interview
- SQL Interview Questions for 5+ Years Experience
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
Random Blogs
- Types of Numbers in Python
- Exploratory Data Analysis On Iris Dataset
- Quantum AI – The Future of AI Powered by Quantum Computing
- How to Become a Good Data Scientist ?
- Best Platform to Learn Digital Marketing in Free
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- Transforming Logistics: The Power of AI in Supply Chain Management
- The Beginner’s Guide to Normalization and Denormalization in Databases
- Python Challenging Programming Exercises Part 3
- Top 15 Recommended SEO Tools
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
- Generative AI - The Future of Artificial Intelligence
- Python Challenging Programming Exercises Part 2
- Government Datasets from 50 Countries for Machine Learning Training
- Datasets for Exploratory Data Analysis for Beginners
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset