1 year ago by: matt
So this is an issue that a few people on the forums and github have reported. Common scenario would be searching or filtering where you are adding additional parameters into your request. Something like the following:
http://mydomain.com/articles?sort=desc
Now you would expect the following output if you have your Paginator set up correctly:
<?php echo $page->next ?> //Output ?page=2&sort=desc
However that is currently not the case. Phalcon paginator will ignore any additional URL parameters and only output ?page=2.
So here's a quick mockup I created to solve the issue for the Paginator\Adapter\QueryBuilder. The exact same solution can be used for the Model Paginator if you want to override it.
<?php
namespace Lib\Paginator\Adapter;
use Phalcon\Http\Request;
use Phalcon\Paginator\Adapter;
class QueryBuilder extends Adapter\QueryBuilder
{
/**
* Returns a slice of the resultset to show in the pagination
*/
public function getPaginate()
{
$page = parent::getPaginate();
if ($this->_config['with_params'] === true)
{
$page->firstQuery = $this->buildParamsQuery($page->first);
$page->beforeQuery = $this->buildParamsQuery($page->before);
$page->nextQuery = $this->buildParamsQuery($page->next);
$page->lastQuery = $this->buildParamsQuery($page->last);
}
return $page;
}
private function buildParamsQuery($page)
{
$request = new Request();
$params = $request->get();
$params['page'] = $page;
$url = $params['_url'];
unset($params['_url']);
$url .= '?' . http_build_query($params);
return $url;
}
}
$paginator = new QueryBuilder(array(
'builder' => $builder,
'limit' => 5,
'page' => $currentPage,
'with_params' => true,
)
);
Now in your view replace $page->next with $page->nextQuery etc.. and you have your URL parameters kept alongside your pagination parameters.
$page->firstQuery; //?page=1&sort=asc $page->nextQuery; //?page=2&sort=asc $page->beforeQuery; //?page=1&sort=asc $page->lastQuery; //?page=6&sort=asc
If I find some free time I will put in a pull request to the Phalcon Github to add this functionality into the core and update this post with a link to the documentation.
- Github
- LinkedIn
- Youtube