22
votes

Right away I would say, that I read this question Doctrine2 Paginator, but it doesn't give me enough information regarding the title of my question.

When I used Doctrine1 I was getting the result with such code for example:

$list = $this->query
    ->addSelect( 'SQL_CALC_FOUND_ROWS *' )
    ->offset( ( $this->currentPage - 1 ) * $this->perPage )
    ->limit( $this->perPage )
    ->execute( array(), \Doctrine_Core::HYDRATE_ARRAY_SHALLOW );

$totalRecords     = SqlCalcFoundRowsEventListener::getFoundRowsCount();
$this->totalPages = ceil( $totalRecords / $this->perPage );

and it was great.

Now, when using Doctrine2 I'm confused on how should I get total amount of records with same query as limited result for current page.

Any help/advice would be greatly appreciated.

2
Will eventually answer tomorrow - for now please check the tests for the paginator at github.com/doctrine/doctrine2/blob/master/tests/Doctrine/Tests/…Ocramius
Looked at tests, but there are no tests, that set limitation to query before passing it to paginator. Maybe I misunderstood something.Eugene

2 Answers

53
votes

The paginator usage is as following:

$paginator  = new \Doctrine\ORM\Tools\Pagination\Paginator($query);

$totalItems = count($paginator);
$pagesCount = ceil($totalItems / $pageSize);

// now get one page's items:
$paginator
    ->getQuery()
    ->setFirstResult($pageSize * ($currentPage-1)) // set the offset
    ->setMaxResults($pageSize); // set the limit

foreach ($paginator as $pageItem) {
    echo "<li>" . $pageItem->getName() . "</li>";
}
-1
votes

Or some other loop:

    for ($i=0; $i < $pagesCount; $i++) {
        if ($currentPage == ($i+1)) {
            $pagination1 .= '<li class="active"><a href="'.\URL::current().'?pagina='.($i+1).'" title="">'.($i+1).'</a></li>';
        }else{
            $pagination1 .= '<li><a href="'.\URL::current().'?pagina='.($i+1).'">'.($i+1).'</a></li>';
        }   
    }