Knp paginator没有分页

时间:2016-04-07 21:27:49

标签: symfony knppaginator

我在让Knp分页器前进到下一页时遇到问题。页面导航栏显示正确,如this image中所示(名称是假的),并且排序有效。但是,当我尝试前进到第2页时,即使网址现在如下所示,该视图也会保留在第1页上:my.page/show?page=2

视图模板由AttendeeController调用,它嵌入在 show.html.twig 中:

    <div class="attendance_table">

        {{ render(controller(
        'AppBundle:Attendee:index', { 'request': request, 'id': entity.id }
        )) }}

    </div>

AttendeeController.php

    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Request;

    class AttendeeController extends Controller
    {

        public function indexAction(Request $request, $id)
        {
            $em = $this->getDoctrine()->getManager();
            $attendees = $em->getRepository('AppBundle:Attendee')->findEventAttendees($id);
            $event = $em->getRepository('AppBundle:Event')->findOneById($id);
           $paginator  = $this->get('knp_paginator');
           $pagination2 = $paginator->paginate(
           $attendees,
           $this->get('request')->query->getInt('page', 1), 10
        );



    return $this->render('Attendee/index.html.twig', array(
        'pagination2' => $pagination2,
        'event' => $event,
    ));
}

}

控制器从AttendeeRepository调用函数 findEventAttendees ,该函数找到与事件关联的与会者:

    public function findEventAttendees($id)
{
    $em = $this->getEntityManager();
    $qb = $em->createQueryBuilder()
        ->select('a')
        ->from('AppBundle:Attendee', 'a')
        ->leftJoin('a.event', 'e')
        ->where('e.id = :id')
        ->setParameter('id', $id);

    return $qb->getQuery();
}

分页视图由参加者/ index.html.twig 呈现:

    {% if pagination2.getTotalItemCount > 0 %}
    <table class="records_list table">
        <thead>
        <tr>
            <th {% if pagination2.isSorted('a.firstName') %} class="sorted" {% endif %}>
                {{ knp_pagination_sortable(pagination2, 'Name', 'a.firstName') }}
            </th >
            <th {% if pagination2.isSorted('a.uni') %} class="sorted" {% endif %}>
                {{ knp_pagination_sortable(pagination2, 'UNI', 'a.uni') }}
            </th>
        </tr>
        </thead>
        <tbody>
        {% for attendee in pagination2 %}
            <tr>
                <td>{{ attendee.firstName }} {{ attendee.lastName }}</td>
                <td>{{ attendee.uni }}</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>

    {# display navigation #}
    <div class="text-center">
        {{ knp_pagination_render(pagination2) }}
    </div>

{% else %}
    <h2>Sorry, no attendees were found for the specified event.</h2>
{% endif %}

感谢您的任何提示!

1 个答案:

答案 0 :(得分:2)

在控制器中,使用作为参数传递的Request对象,而不是从容器中检索的Request。

所以试试这个:

$request->query->getInt('page', 1); 

而不是:

$this->get('request')->query->getInt('page', 1);

从容器中获取请求是一个不推荐使用的功能。在this annuncement,Fabien看到了:

  

很难说在服务容器中处理请求   至少。为什么将请求注入服务很困难?   因为在一个PHP进程中可以有多个请求   (想想子请求。)所以,在容器的生命周期中,   请求实例更改。

希望这个帮助