CiviCRM has its own pagination class which makes it quite easy for you to use pagination on your pages. In this tutorial I will explain how you could add pagination to your own pages and forms.
The first thing you have to notice that there is a Util class for pagination: CRM_Utils_Pager
This class requires some setup code and you have to pass this class to the template for the rendering.
First select the total numbers you have
$total = CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM civicrm_contact");
Then you have to configure the pager and initialize it. You have to define how many items per page you are showing and which page you showing.
$params['total'] = $total; $params['currentPage'] = $this->get(CRM_Utils_Pager::PAGE_ID); $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT; $params['status'] = ts('Contacts %%StatusMessage%%'); $this->_pager = new CRM_Utils_Pager($params);
The most important thing is to retrieve the current page from the request. You could do that in your form or page with the following code
$params['currentPage'] = $this->get(CRM_Utils_Pager::PAGE_ID);
The CRM_Utils_Pager class has a constant which names the parameter in your request and with $this->get you retrieve the data from the request.
Now you have to create the actual query with a limit and a offset.
list($offset, $limit) = $this->_pager->getOffsetAndRowCount(); $queryParams[1] = array($offset, 'Integer'); $queryParams[2] = array($limit, 'Integer'); CRM_Core_DAO::executeQuery("SELECT * FROM civicrm_contact LIMIT %1, %2", $queryParams)
Then there is one thing left and that is pass the pager to your template and then include the pager inyour template.
$this->assign_by_ref('pager', $this->_pager);
And in your template add:
{include file="CRM/common/pager.tpl" location="bottom"}
That is it!