【问题标题】:Doctrine pagination - restricting the number of pages shown?教义分页 - 限制显示的页数?
【发布时间】:2024-04-17 03:40:02
【问题描述】:

查看了相关文档,但找不到我需要的明确答案,因此不确定是否可行,但这是我想要实现的目标:

我有一个客户列表,在我的 Symfony2 项目中分页。目前数据库中有几百个,但预计会增长。目前有 22 页的客户,我使用的分页是标准的 Doctrine2 分页。我在控制器中显示客户端的功能如下:

$em = $this->getDoctrine()->getManager();
$client_repo = $em->getRepository('AppBundle:Clients');
$clients = $client_repo->findByAccountStatus($status);
$message = false;
$page = $request->get('page');
$total_clients = count($clients);
$per_page = 20;
$total_pages = ceil($total_clients/$per_page);

if (!is_numeric($page)) {
    $page = 1;
} else {
    $page = floor($page);
}
if ($total_clients <= $per_page) {
    $page = 1;
}
if (($page * $per_page) > $total_clients) {
    $page = $total_pages;
}
$offset = 0;
if ($page > 1) {
    $offset = $per_page * ($page - 1);
}

$dql = "SELECT c FROM AppBundle:Clients c WHERE c.accountStatus = '".$status."'";
$query = $em->createQuery($dql)
    ->setFirstResult($offset)
    ->setMaxResults($per_page);

$paginator = new Paginator($query, $fetchJoinCollection = false);


return $this->render('AppBundle:tables:clientstable.html.twig', array(
    'clients' => $paginator,
    'total_pages' => $total_pages,
    'current_page' => $page
));

而我的twig文件实现分页如下:

{% if total_pages > 1 %}
<div class="text-center">
    <ul class="pagination">
        {% for i in 1..total_pages %}
            {% if loop.first %}
                <li class="prev{% if current_page==1 %} disabled{% endif %}"><a href="{% if current_page>1 %}{{ path('app_show_clients', {'page':current_page-1}) }}{% else %}javascript:void(0){% endif %}">«</a></li>
            {% endif %}
                <li{% if current_page==loop.index %} class="active"{% endif %}><a href="{{ path('app_show_clients', {'page':loop.index}) }}">{{ loop.index }}</a></li>
            {% if loop.last %}
                <li class="next{% if current_page == total_pages %} disabled{% endif %}"><a href="{% if current_page < total_pages %}{{ path('app_show_clients', {'page':current_page+1}) }}{% else %}javascript:void(0){% endif %}">»</a></li>
            {% endif %}
        {% endfor %}
    </ul>
</div>
{% endif %}

目前,分页器显示所有页面,但在几个月内可能会有两倍的客户数量时,页面数量会在屏幕上溢出,看起来很乱。我想知道的是,有没有办法限制分页块中任何时候显示的页面数,例如,它显示 10 页,但是当您单击一个页面时,它会提供更多信息,例如:

[>]

然后,当您单击第 3 页时,它可能如下所示:

[>]

或者类似的?

希望我解释得足够好!

迈克尔

【问题讨论】:

    标签: symfony doctrine-orm pagination paging


    【解决方案1】:

    不要让自己复杂化,使用https://github.com/KnpLabs/KnpPaginatorBundle,非常易于使用,所有模板都是可配置的。已经与 bootstrap 2 和 3 集成。如果您愿意,可以使用其他,但这对我有用很多次。

    【讨论】:

      【解决方案2】:

      你必须在视图中添加类似的东西:

      {% for p in range(max(current_page-3, 1), min(current_page+3, total_pages)) %}
          <a {% if p == current_page %} class="current-page"{% endif %} href="{{ path('route_name', {'page': p})) }}">{{ p }}</a>
      {% endfor %}
      

      希望对你有帮助。

      【讨论】: