Category Archives: Yii 2 Custom Widgets

Yii 2 Custom Widgets

I hope everyone’s new year is off to a great start. Special thanks to everyone from around the world who has purchased Yii 2 For Beginners, I really appreciate your support. I also appreciate the positive ratings and reviews I’ve been getting, for example the two I got recently on GoodReads.com.

Your positive feedback keeps me motivated and recently I added over 100 pages of new material to the book. Anyone who purchases the book gets free updates for the life of the book, just log into your leanpub.com account to get the latest.

One of the recent additions to the book had to do with creating your own widgets. For those who are unfamiliar with Yii 2’s widgets, they are very handy for presenting data in the view. Yii 2 ships with a number of time-saving widgets that cover everything from navigation, grid results, pagination etc.

An implementation of a widget could start with a single line of code in the view:

echo GridView::widget(['dataProvider' => $dataProvider,]);

But typically with GridView, you will have a lot of customization of the columns and data-display formats, so the array inside the method signature can grow quite a bit.

Here’s what you might see from a basic user model in a backend admin view:

echo GridViewWidget::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],

'id',
'username',
'email:email',
'status',
'created_at',

['class' => 'yii\grid\ActionColumn'],

],
]);

I’m not going to go into too much detail here, but you can see that the data is provided by the $dataProvider, and I don’t know how it can possibly be more intuitively named, so you have to love that.

The $dataProvider instance is being handed in from the controller, so you don’t have to supply any additional logic in the view. Next you supply it with a filter model, which is again handed in from the controller. Then you simply list the attributes you want to appear in the view.

The format of the email attribute creates a mailto link, and there are many ways to manipulate the appearance of the data.

We are also supplying classes for the look of the columns and a separate class for the ActionColumn, which contains icons and links to view, update, and delete individual records. This is just incredibly powerful out-of-the-box, especially if you are doing rapid prototyping of an admin area. We setup a much more complex version of this in the book, but you get the basic idea here.

One of the big points here is that you don’t need to put a foreach loop in the view, the widget takes care of it for you. So the widget is more of a configuration tool, not really doing much logic, and this helps to make your views incredibly clean. WordPress is chomping the code, so I can’t show you the shortcut echo tags, but you can use the shortcut because this is all really just one line, a bunch of settings handed into the array that sits in the method signature.

You will see very quickly how easy a widget is to place inside of a view, so much so that it spoils you a little. You're going to want a widget for everything.

While that’s not really practical, the good news is that you can easily create your own custom widgets. This article is more of an overview than a tutorial, so I’m not going to cover the complete setup, but I will give you an idea how it works.

Your widgets will extend Widget, with Yii 2 providing the perfect class structure for you to create these wonderful helpers. You start by overwriting your widget's two main methods, init and run.

Init just does the logic you want to perform, the result of which will be stored in the properties that you have named in the class. Then to pass the property values to the widget view, you use the run method, which renders the view with the values you have calculated in the init. The widget view is typically only a partial, which is going to sit inside of another view, making it portable and reusable.

So if you want to create a widget holding a top ten list from your content, and then use it multiple times on your site with just a single line call inside your view, you can do it. This is powerful stuff.

The cool part is how you hand in configuration from your widget call to the widget class itself. The Widget class is already structured to be able to receive an array. So you just set the array as a class property, and when the widget is called, the values of the array get handed in. Then you can use these values in the init to perform the logic you need for formatting the data.

Example:

echo MyWidget::widget(['settings' => ['pageSize' => 3]])

So imagine you wanted to build a widget where you had some results and you wanted to control the page size for pagination. In your MyWidget class, you would have a property declared as $settings = [];

In the code example above, you can see that we created the key/value pair that goes in this array, so this is assigned to the class property when the widget is called. So in your init method, you could perform logic using $this->settings[‘pageSize’] however you want. It’s that simple to move the data in. If this isn’t clear from my description, don’t worry, when you try it for yourself, you will see how it all fits together.

Although your run method need not include a view, it’s better to do it that way if you are creating output that involves html or css, which will most likely be the case. Then you just need to remember that when using the render method from within run, you need to access the properties via keyword $this, because unlike a controller, they will not be available to you otherwise.

The only other slightly tricky part to all this is setting up the application to have visibility on your custom components, which will be in its own components folder, and have its own namespace. I provide a full working example in the book, but that’s too much for here, so consult the Guide for instructions on that. Their widget section is fairly easy to follow.

Once you’ve had a chance to work with Yii 2’s widget architecture, it’s difficult to imagine coding life without it. I see it as yet another huge advantage of selecting Yii 2 as your choice for framework.

Advertisements