- 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
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:
- 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
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- AI & Space Exploration – AI’s Role in Deep Space Missions and Planetary Research
- Convert RBG Image to Gray Scale Image Using CV2
- Python Challenging Programming Exercises Part 1
- Datasets for Exploratory Data Analysis for Beginners
- String Operations in Python
- How to Become a Good Data Scientist ?
- Variable Assignment in Python
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- Career Guide: Natural Language Processing (NLP)
- Deep Learning (DL): The Core of Modern AI
- Government Datasets from 50 Countries for Machine Learning Training
- SQL Joins Explained: A Complete Guide with Examples
- Internet of Things (IoT) & AI – Smart Devices and AI Working Together
- The Ultimate Guide to Data Science: Everything You Need to Know
- Top 10 Knowledge for Machine Learning & Data Science Students
Datasets for Machine Learning
- 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
- Bitcoin Heist Ransomware Address Dataset