Question

I have written custom queries in my repository class and they returns arrays then I do some processing on those arrays then displays to twig.

So please suggest the best pagination method to apply paging on this custom queries resulting in arrays.

I am new to symfony2, does default paging will work and how? I mean what syntax, please provide example.

No correct solution

OTHER TIPS

You should try Knp Paginator. It is simple and customizable. Simple code example (Doctrine MongoDB ODM):

// Pay attention: query, not result.
$query = $this->getRepositoryOfferKind()->createQueryBuilder()
  ->field('is_private')->equals(false)
  ->field('is_deleted')->notEqual(true)
  ->sort('updated_at', 'DESC')->getQuery();

$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate($query, $request->get('page', 1), 20);
/* @var $pagination SlidingPagination */
$pagination->setUsedRoute('admin_offer_kind_index');
$pagination->setPageRange(10);

return array(
  'objects' => $pagination,
);

And twig:

    <table>
      <thead>
      <tr>
        <th>Title</th>
      </tr>
    </thead>
    <tbody>
    {% for object in objects %}
        <tr>
            <td>
                {{ object.title }}
            </td>
        </tr>
    {% else %}
        <tr>
            <td>No data</td>
        </tr>
    {% endfor %}
    </tbody>
    <tfoot>
    <tr>
        <td>
            {{ knp_pagination_render(objects) }}
        </td>
    </tr>
    </tfoot>
</table>

You can try this native solution

public function getPagination($someValue, int $page = 1, $limit = 20, $sort = "createdAt", $sortOrder = 'DESC')
{
     $qb = $this->createQueryBuilder();
     $qb->field('some_filed')->equals($someValue);
     // and so on
     return $qb->sort($sort, $sortOrder)
        ->skip(($page - 1) * $limit)
        ->limit($limit)
        ->getQuery()->toArray();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top