How to create custom widget in Yii2

This tutorial will show you how you can create your own custom widget in Yii2. Widgets are reusable blocks and they are used in your views. The main advantage of Widget is you can write once and reuse it wherever you need it in your view.

To create a custom widget we must extend the base widget yii\base\Widget and we have to override the init() and/or run() methods of base widget.

Here are the simple steps for creating a custom widget.

Step1:
Make a folder named “components” in your project root folder.

step2:
Create a file with desired widget name inside components folder and copy paste the below code and change the class name in the code. Example – Mywidget.php

In this class, Mywidget is our custom widget. app\components is the namespace of this class and Mywidget is a class name. Using both namespace and class name, we can access this widget like app\components\Mywidget.

Create a views folder inside components folder. Create a view file named myWidget.php in components/views folder and put your content in it.

Step3:
You are done!. Now you can use your widget inside any of your app views.

Usage example –

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 vote
Article Rating
Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Santanu Kumar Manna
Santanu Kumar Manna
3 years ago

Thanks It is very helpful….

Pasquale Pellicani
Pasquale Pellicani
3 years ago

How can call renderPartial from a custom widget ?

Swapnil Akolkar
Swapnil Akolkar
1 year ago

Hi thank you , I have little query how it is about in yii2 advanced templates. I gt some errors in Advanced template Class ‘appcomponentsSidebar’ not found

I am creating Sidebar widget. Can anyone help me to sort out the paths and namespace wrt Yii2 Advanced templates thank you !!!

DMCA.com Protection Status
3
0
Would love your thoughts, please comment.x
()
x