Download Pagination code in CakePHP3 and Mysql

In this article, you will learn how to use pagination features in CakePHP. CakePHP uses Paginator component in Controller to help you in paginated queries and uses Paginator helper in the view files to make links and buttons for pagination. Pagination is very important where we need to show several block of content.

(You can also Read: Download Pagination in PHP and MySql With Example)

The simple way to use paginator component in cakePHP3

Step 1 :

Go to your Controller file of the model you want to paginate, and load PaginatorComponent. I will load it in TopicsController.php.

<?php
public function initialize()
    {

        parent::initialize();

        $this->loadComponent('Flash'); // Include the FlashComponent
		$this->loadComponent('Paginator');
				
    }

?>

Step2 :

Define the default options of pagination query in the pagination variable in Controller

classTopicsController extends AppController
{

	public $paginate = [
		'limit' => 5,
		'order' => [
		'Topics.title' => 'asc'
		]
	];
//… other functions

We use ‘limit’ key to determine the maximum number of records on every page .The default limit in CakePHP is 100 record in page.
’ order’ key defines the model field to order on

Step3 :

Use pagination in index() function to apply pagination sets in topics object.

TopicsController.php

<?php

namespace App\Controller;

use App\Controller\AppController;
use Cake\Cache\Cache;
classTopicsController extends AppController
{

	public $paginate = [
		'limit' => 5,
		'order' => [
		'Topics.title' => 'asc'
		]
	];
	
public function initialize()
    {

        parent::initialize();

        $this->loadComponent('Flash'); // Include the FlashComponent
		$this->loadComponent('Paginator');
				
    }
public function index()
    {
		// find('all') get all records from Topics model
		// We uses set() to pass data to view 
		$topics = $this->paginate($this->Topics);
		$this->set('topics', $topics);		
    }
//.. Other functions
?>

In the index.ctp template file, we will add pagination view code that make pages url ,page number, and pagination statics.

/Templates/Topics/index.ctp

<h1>Blog topics</h1>
<p><?= $this->Html->link('Add Topic', ['action' => 'add']) ?></p>
<p>
<?php
// Pagination statics 
	echo $this->Paginator->counter('Page {{page}} of {{pages}}, showing {{current}} records out of
{{count}} total, starting on record {{start}}, ending on {{end}}');
	?>
</p>	
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
<th>Actions</th>
</tr>

<!-- Here's where we loop through our $topics query object, printing out topic info -->

<?phpforeach ($topics as $topic): ?>
<tr>
<td><?= $topic->id ?></td>
<td>
<?= $this->Html->link($topic->title, ['action' => 'view', $topic->id]) ?>
</td>
<td>
<?= $topic->created->format(DATE_RFC850) ?>
</td>
<td>
<?= $this->Form->postLink(
                'Delete',
                ['action' => 'delete', $topic->id],
['confirm' => 'Are you sure?'])
            ?>
<?= $this->Html->link('Edit', ['action' => 'edit', $topic->id]) ?>
</td>
</tr>

<?phpendforeach; ?>
		<tr>
		<td>
		<?php
		// Pagination urls
			echo $this->Paginator->prev('< ' . __('previous'));
			echo $this->Paginator->numbers();
			echo $this->Paginator->next(__('next') . ' >');
		?>
		</td>
		<td>
		</td>
	</tr>
	<tr>
	<?php  if ($this->request->session()->read('Auth.User')){ ?>
		<td><?=$this->Html->Link(__('Log out'),['controller'=>'users','action'=>'logout']) ?></td>
	<?php }else{  ?>
		<td><?=$this->Html->Link(__('Login'),['controller'=>'users','action'=>'login']) ?></td>	
	<?php } ?>
	
	</tr>
</table>

counter() method can take some tokens that represent pagination values.

 {{page}}  the current page.

{{pages}}  total number of all pages.

{{current}}  current number of records being shown.

{{count}}  the total number of records in the result set.

 {{start}} the number of the first displayed record in the page.

 {{end}}  number of the last record being displayed.

You can also add sorting urls in the head of the topics table using sort()function.It takes two parameters the name of the field used for ordering and the title of the link.

<?= $this->Paginator->sort('id', 'Topic ID') ?>

Custom pagination

You can make and use your custom pagination in CakePHP. In config folder create a PHP file to save your custom pagination format. I created a custom pagination that will be familiar with twitter bootstrap.

bootstrap-paginator.php

<?php

$config = [

	    'nextActive' => '<li>
<a href="{{url}}" aria-label="{{text}}">
<span aria-hidden="true">&raquo;</span>
</a>
</li>',
    'nextDisabled' => '<li class="next disabled"><span>{{text}}</span></li>',
    'prevActive' => '<li>
<a href="{{url}}" aria-label="{{text}}">
<span aria-hidden="true">&laquo;</span>
</a>
</li>',
    'prevDisabled' => '<li class="prev disabled"><span>{{text}}</span></li>',
    'counterRange' => '{{start}} - {{end}} of {{count}}',
    'counterPages' => '{{page}} of {{pages}}',
    'first' => '<li class="first"><a href="{{url}}">{{text}}</a></li>',
    'last' => '<li class="last"><a href="{{url}}">{{text}}</a></li>',
    'number' => '<li ><a href="{{url}}">{{text}}</a></li>',
    'current' => '<li class="active disabled" ><a href="{{url}}">{{text}}</a></li>',
    'ellipsis' => '<li class="ellipsis">...</li>',
    'sort' => '<a href="{{url}}">{{text}}</a>',
    'sortAsc' => '<a class="asc" href="{{url}}">{{text}}</a>',
    'sortDesc' => '<a class="desc" href="{{url}}">{{text}}</a>',
    'sortAscLocked' => '<a class="asc locked" href="{{url}}">{{text}}</a>',
    'sortDescLocked' => '<a class="desc locked" href="{{url}}">{{text}}</a>',

];
?>

To use your custom pagination, Load it in AppView.php

<?php
//In AppView.php
public function initialize()
{
...
$this->loadHelper('Paginator', ['templates' =>bootstrap-paginator']);
}
?>

The last code tells the Paginator helper to load template format from bootstrap-paginator.php file in /config/ path.
Have a nice pager with CakePHP. Feel free to ask in comments.

Share this Article on Social Media

All of my Scripts are ready to customized as per your requirement. Feel free to contact for script customization.

Contact me at discussdesk@gmail.com

"Note : It will be charged as per your customization requirement :)"

Get Updates, Scripts & Other Tutorials to Directly to your Email

Over 20000+ Happy Readers already subscribed. (We don't send spam email). Every email subscriber can get our latest updates and download our 100+ scripts.

Comments