Posted  by 

Yii Pager

  1. Yii Pager Examples
  2. Yii Pager Cgridview

The Yii Book If you like my writing on the Yii framework, you'll love 'The Yii Book'! The first thing you’ll need to know to use JavaScript and jQuery in Yii is how to add JavaScript to a Web page. As with any standard Web page, there are two primary options. This is the Yii Framework API Documentation. Here you will find detailed information about all classes provided by the Framework. Below you find a list of the existing classes, interfaces, and traits, ordered.

This is the part2 of the tutorial. In this part we will register JavaScript to make the custom pager widget work.

Yii Pager

Take a glance again at the screenshot about what effect we will create.

We've finished rendering work of the new custom DemoPager widget in part1. Next we'll add JavaScript support in this part.

8 Register Widget Assets

Generally, the required JavaScript helper files or CSS files by a Yii2 widget should be packaged with widget together. This can be achieved by using yiiwebAssetBundle.

8.1 Register JS In DemoPagerAsset

Register JavaScript file in DemoPagerAsset.php.

8.2 Register DemoPagerAsset In DemoPager Widget

To use the JavaScript and CSS files registered in DemoPagerAsset, we still need register DemoPagerAsset itself to DemoPager widget. We do this step in run method of DemoPager widget.

After registering, Yii2 will echo script tags automatically before HTML end body tag.

9 demopager.js

Yii Pager Examples

Implement our demopager.js.

Yii Pager Cgridview

  • when user select a new page size, we'll replace page size parameter in query strings of current URL with new selected size and then refresh browser;
  • when user input a new target page number and press enter key, we'll replace page parameter in query strings of current URL with new page number, then jump to the new URL;

Next, we need call above init function and pass pageSizeParam, pageParam, url parameters from PHP to JavaScript. We use registerJs method of yiiwebView to do the magic.

registerJs method will output inline JavaScript code blocks, which looks like in picture below.

10 Usage

To allow flexible page size, you should not hard coded the page size in your controller.

Then use DemoPager with ListView in your view file.

Check the result by accessing URL: http://YOUR_HOST_OR_APP/index.php?r=test/test. Software free download games.

Yii Pager

11 Style

You may discover that our DemoPager is ugly now because there's no CSS style yet.

There are two ways to style DemoPager widget.

  • Write CSS styles in YOUR_APP/widgets/demopager/assets/css/demopager.css, and package this CSS file together with DemoPager widget class. But this way lose flexibility if widget user want to add dynamic styles;
  • Pass CSS class name or CSS styles directly as HTML options while using DemoPager widget.

I'll demonstrate the second method here.

That's all, now our DemoPager looks really good. Source codes are available.