Welcome to Findnerd. Today we are going to discuss pagination in CakePHP 3. If you have hundreds of records in one page then you need to implement the pagination for better user experience. Pagination is a technique to divide the records in multiple pages. Pagination may be difficult process for a developer so CakePHP provides a component in a controller that is paginatorComponent and PaginatorHelper in a view for generating a paginate links or buttons.
You can set the different options as well as conditions using $paginate variable in controller. We can set the limit to display the records on single page, can set the order key for sorting purpose and can set the fields as well. Please have a look.
class CommentsController extends AppController
{
public $paginate = [
'fields' => ['Comments.id', 'Comments.created'],
'limit' => 10,
'order' => [
'Comments.created' => 'asc'
]
];
public function initialize()
{
parent::initialize();
$this->loadComponent('Paginator');
}
}
In above controller we are loading component Paginator using initialize method and set the different query options such as fields,order and limit. Now we will use paginate() method to get the paginated records. Please have a look.
class CommentsController extends AppController
{
public function comments_list()
{
$this->set('comments', $this->paginate());
}
}
In above code we have set the variable comments. Now we can use this variable in comments_list.ctp to paginate the records.
Paginate() method by-default uses the default model but you can also use other model as well. Please have a look.
public function comments_list()
{
$query = $this->Comments->find('all')->where(['comment_id' => 1]);
$this->set('comments', $this->paginate($query));
}
maxLimit is the option in $paginate variable to set the maximum number of rows that can be fetched. By-Default maximum 100 rows can be fetched if you do not set the maxLimit value. When you try to access the page which does not exist then paginator component will throw the exception that is NotFoundException. Please have a look.
use Cake\Network\Exception\NotFoundException;
public function index()
{
try {
$this->paginate();
} catch (NotFoundException $e) {
// Do something here like redirecting to first or last page.
// $this->request->params['paging'] will give you required info.
}
}
You can also set the additional association by using contain key option. Please have a look.
function comments_list()
{
$this->paginate = ['contain'=>'authors'];
this->set('comments',$this->paginate($this->Comments));
}
0 Comment(s)