Sharing technology, ideas, insights!
Call: +91 710 466 0336         Email: hello@sanisoft.com

Blog

Change markup for pagination in CakePHP 3

Yes, it was possible to change markup for pagination in CakePHP 2.x but it involved passing the markup in options array to the numbers method of the paginator helper. So you ended up with something like

It worked but it always felt kludgy and was error prone.

CakePHP 3 introduces an elegant solution to this problem in the form of PaginatorHelper templates. PaginatorHelper templates allow you to easily separate the markup from your code and keep your code DRY. Let us try and use them. In this very short HowTo we will change the Pagination section to look from this

li_numbers

to this.

option_numbers

Step 1

Create a file called paginator-templates.php in the src/Config/ folder.

Step 2

Put the following code in the paginator-templates.php (don’t forget to add the php opening tag)

Step 3

Open the template which has pagination eg: Posts/index.ctp from the previous blog entry and replace the following lines

with

The significant line in the above snippet is $this->Paginator->numbers(); everything else is just a simple form which uses GET method. I could have used the form helper to create the start and end of the form but it does not serve any purpose to use the helper here,

Step 4

In your controller add the following

That is it! If you reload your page you should see a select input which allows you to go to any page you select on clicking the “Go” button. Yes, I know that the looks of what you have got is probably very different from what I have shown above but that is just Bootstrap CSS applied to the form elements, I leave that as an exercise to you. If you have not already read the previous post about using themes in CakePHP 3 you can do so now.

Extras

Here we changed the pagination markup for the entire app. We can do this on per theme basis by loading the templates from plugins thus

Putting the Paginator directive in the app controller of the plugin will not work because the app controller of the plugin never gets executed when the plugin is acting as a theme

The templates can be changed at run-time but the code gets ugly again

The following are the default templates available, you can change any or all of them to suit your purpose

About the Author

Dr. Tarique Sani is a pediatrician and forensic expert by education. He is a PHP programmer of 'wrote the book' caliber and has to his credit several very popular open source as well as commercial PHP projects. He leads a team of dynamic programmers at SANIsoft who have in-depth understanding of Web scalability, development tools and usability practices with strong developmental skills in PHP, MySQL/PostgreSQL, HTML, Javascript, and Linux/Apache

3 comments

  1. Pingback: CakePHP3.0への移行の準備メモ | X->A->O

Leave a Reply