我试图使用捆绑包KnpPaginator在我的网站上创建一个分页。在我的存储库中,我创建了一个查询:
public function getProductsOrderByDateDesc($id_category = null, $max = null){
$qb = $this->createQueryBuilder('p')
->orderBy('p.created_at', 'DESC');
if($max) {
$qb->setMaxResults($max);
}
if($id_category) {
if(is_array($id_category)){
$aIdCategory = implode("','",$id_category);
$qb->andWhere('p.category IN (:ids)')
->setParameter('ids', $aIdCategory);
}else{
$qb->andWhere('p.category = :category_id')
->setParameter('category_id', $id_category);
}
}
$query = $qb->getQuery();
return $query->getArrayResult();
}
在我的控制器中:
$repositoryProduct = $em->getRepository('ShopDesktopBundle:Product');
$aProducts = array();
$aProducts = $repositoryProduct->getProductsOrderByDateDesc($id);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$aProducts,
$this->get('request')->query->get('page', 1),
3
);
return $this->render('ShopDesktopBundle:Category:category.html.twig',array(
'aProducts' => $aProducts,
'pagination' => $pagination
));
在视图中,我只显示此分页:
<div class="navigation">
{{ knp_pagination_render(pagination) }}
</div>
问题是,总是显示所有产品,而不仅仅是对我的示例为3的限制。例如:我有9种产品,limit=3,页码是正确的"123",但每一页我都看到所有9种产品请帮帮我!Thx提前
几乎正确,但是您必须使用分页对象而不是"aProducts"。在您看来,使用以下代码:
{% for product in pagination %}
<tr {% if loop.index is odd %}class="color"{% endif %}>
<td>{{ product.id }}</td>
<td>{{ product.title }}</td>
</tr>
{% endfor %}
请参阅文档中"查看"下的更多信息:https://github.com/KnpLabs/KnpPaginatorBundle