使用 slug 时 Knp Paginator Bundle 路由错误

Knp Paginator Bundle route error when using slug

我想为 table 实现 Knp 分页。

这是我编辑文档的页面,所以我的路线是这样的: @Route("/document/edit/{id}/") 并且根据文档,有不同的 ID。 页面上有几个面板,其中一个包含 table 个不同的机构。为此 table 我使用了 knp_paginator:

/**
    * @var $paginator \Knp\Component\Pager\Paginator
    */
    $paginator = $this->get('knp_paginator');
    $agencyTable = $paginator->paginate(
      $docAgencies,
      $request->query->getId('page', 1),
      5
    );

$docAgencies 就是这样定义的,所以它不是查询,但这是我获取信息所需的方式!

  $document = $em->getRepository('DocumentBundle:Document')->findOneByIdInContext($id, $currentuser);
      $docAgencies = $document->getAgencies();

第一次访问该页面时,一切正常,显示 table 的第一页,但是当我尝试单击 table 的另一页时,我收到错误消息:

Controller "DocumentBundle\Controller\Document\EditController::editAction()" requires that you provide a value for the "$id" argument (because there is no default value or because there is a non optional argument after this one).

我的路线是这样的:

http://localhost/sp/web/app_dev.php/document/document/edit?page=3

所以文档的id刚刚被删除,没有任何内容可以访问。 我试图像在其他 Whosebug 问题中推荐的那样向我的路线添加一个 /{page} 但这似乎对我也不起作用。 我就是这样尝试的:

  * @Route("/document/edit/{id}/{pag}", name="documentBundle_edit", requirements={"id" = "\d+", "pag" = "\d+"}, defaults={"id" = 0, "pag":1})

editAction:

    public function editAction(Request $request, $id, $pag) {
..

并在分页函数内:

  $paginator = $this->get('knp_paginator');
    $agencyTable = $paginator->paginate(
      $docAgencies,
      $pag,
      5
    );

知道为什么这不起作用吗?

更新 树枝视图

    {% block content %}

{{ form_start(form) }}

<div class="row">
{% include 'Form/form_errors_banner.html.twig' %}
<div class="col-md-6">
  <div class="panel panel-default">
    <div class="panel-body">
      <legend>{{ 'header.info'|trans }}</legend>
      {% include 'DocumentBundle:Panels:DocumentInfo.html.twig' %}
    </div>
  </div>

  <div class="panel panel-default">
    <div class="panel-body">
      <legend>{{ 'label.comments'|trans }}</legend>
      {% include 'AppBundle::CommentTable.html.twig' with {
      'entity': document,
      'add_comments': true
      } %}
    </div>
  </div>

</div>

<div class="col-md-6">
  <div class="panel panel-default">
    <div class="panel-body">

      <legend>{{ 'label.distribution'|trans }}</legend>


<div id="upload_profile_no">
{% trans_default_domain 'AppBundle' %}

{# CONFIG #}
{% if deleteButton is not defined %}
    {% set deleteButton = true %}
{% endif %}
    {{ form_label(form.agencies) }}<br>
    {{ form_widget(form.agencies) }} <br> <br>
    <table class="footable">
        {# header fields #}
        <thead>
            <tr>
                <th data-field="iata">{{ 'label.iata'|trans }}</th>
                <th data-field="name">{{ 'label.name'|trans }}</th>
                <th data-field="city">{{ 'label.city'|trans }}</th>
                <th data-field="country">{{ 'label.country'|trans }}</th>
                {% if deleteButton %}<th data-field="delete"></th>{% endif %}
            </tr>
        </thead>

      {% block tablebody %}
        {# body fields #}
        <tbody>
            {% for agency in docAgencies %}
                <tr>
                    <td data-title="iata" data-market="{{ agency.market.id }}"><a href="{{ path('appBundle_agencyEdit', {'id': agency.id}) }}">{{ agency.id }}</a></td>
                    <td data-title="name">{{ agency.account }}</td>
                    <td data-title="city">{{ agency.cityName }}</td>
                    <td data-title="country">{{ agency.market.id }}</td>
                    {% if deleteButton %}
                        <td data-title="delete">
                            <button class="btn btn-danger btn-xs btn-remove-row" type="button" data-index="{{ agency.id }}">
                                <span class="glyphicon glyphicon-minus"></span>
                            </button>
                            <button class="btn btn-primary btn-xs btn-undo-remove hidden" type="button" data-index="{{ agency.id }}">
                                <span class="glyphicon glyphicon-repeat"></span>
                            </button>
                        </td>
                    {% endif %}
                </tr>
            {% endfor %}
        </tbody>
    {% endblock %}
    </table>
    {% if docAgencies.pageCount > 1 %}
    <div class="navigation text-center">
        {{ knp_pagination_render(docAgencies) }}
    </div>
    {% endif %}
  </div>

  <br>
  <div class="row">
    <div class="col-md-6">
      {{ form_row(form.airlines, { 'attr': { 'class': 'form-inline'} }) }}
    </div>
    <div class="col-md-6">
      {{ form_row(form.products, { 'attr': { 'class': 'form-inline'} }) }}
    </div>
  </div>

</div>
</div>

<div class="panel panel-default">
  <div class="panel-body">
    <legend>{{ 'label.attachments'|trans }}</legend>
    {% set fileDomain = 'document' %}
    {% include 'AppBundle::AttachmentConfig.html.twig' %}
    {% include 'AppBundle::DisplayAttachments.html.twig' with {'entity': document} %}
    {% include 'AppBundle::FileUpload.html.twig' %}
  </div>
</div>


</div>

</div>


<div class="row">
  {% include 'AppBundle::HelpSubmitButton.html.twig' %}
</div>
  {{ form_end(form) }}
  {% include 'DocumentBundle:Action/UploadProfile:modals.html.twig' %}

{% endblock content %}

分页部分是 table 和 {% for agency in docAgencies %}

**更新 2 ** 我的完整控制器:

class EditController extends Controller {


   /**
    * @Route("/document/edit", name="documentBundle_edit2")
    * @Route("/document/edit/{id}/{pag}", name="documentBundle_edit", requirements={"id" = "\d+", "pag" = "\d+"}, defaults={"id" = 0, "pag" = 1})
    * @Template()
    */

    public function editAction(Request $request, $id, $pag) {

      $currentuser = $this->container->get('security.token_storage')->getToken()->getUser();
      $em = $this->getDoctrine()->getManager();
      $document = $em->getRepository('DocumentBundle:Document')->findOneByIdInContext($id, $currentuser);
      $allComments = $document->getComments();
      $docAgencies = $document->getAgencies();
      $statusRepository = $em->getRepository('DocumentBundle:Status');

      if($this->get('security.authorization_checker')->isGranted('ROLE_DOCUMENT_EDIT') && $document->getStatus()->getName() == 'Effective' && $document->isActive()
      || $this->get('security.authorization_checker')->isGranted('ROLE_CONTRACT_ADMIN')){

        /*
        * GET DOCUMENT FROM DB
        */

        /*
        * CHECK Document
        */
        if($document == null)
        {
          return $this->get('app.error_helper')->throwError('error.404');
        }

        $form = $this->createForm(DocumentEditType::class, $document);

        /*
        * CREATE PAGINATION FOR TABLES
        */
        /**
        * @var $paginator \Knp\Component\Pager\Paginator
        */
        $paginator = $this->get('knp_paginator');
        $agencyTable = $paginator->paginate(
          $docAgencies,
          $pag,
          5
        );
        $agencyTable->setTemplate('DocumentBundle::table_pagination.html.twig');
        $agencyTable->setUsedRoute('documentBundle_edit');
        $agencyTable->setParam('id', $id);
        $commentTable = $paginator->paginate(
          $allComments,
          $pag,
          5
        );
        $commentTable->setTemplate('DocumentBundle::table_pagination.html.twig');

        /*
        * IF REQUEST IS VALID
        */
        $form->handleRequest($request);
        if ($form->isValid()) {

        $effective = date_format($document->getEffective(), 'Y-m-d');
        $expires = date_format($document->getExpires(), 'Y-m-d');
        $now = date('Y-m-d');

        if($now < $effective) {
            $status = $statusRepository->findOneById('3');
        } elseif ($now >= $expires) {
            $status = $statusRepository->findOneById('2');
        } else {
            $status = $statusRepository->findOneById('1');
        }

        $document->setStatus($status);
          $em->flush();
          $this->addFlash(
          'success',
          'The document has been edited!'
          );
          return $this->redirectToRoute('documentBundle_document_list');
        }
        /*
        * DISPLAY Document
        */
        return $this->render('DocumentBundle:Document:edit.html.twig', Array(
          'document' => $document,
          'docAgencies' => $agencyTable,
          'comments' => $commentTable,
          'form' => $form->createView(),
        ));
      } else {
        /*
        * THROW ERROR
        * If the acting user is not allowed to perform this action
        */
        return $this->redirectToRoute('documentBundle_view_document', array(
          'id' => $id
      ));

    }
    }
}

table_pagination.html.twig

<nav>
<ul class="pagination">
  {# Previous #}
  {% if startPage == 1 %}
    <li class="disabled">
      <a href="#" aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
      </a>
    </li>
  {% else %}
    <li>
      <a href="{{ path(app.request.attributes.get('_route'), {'page': startPage - 1}) }} " aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
      </a>
    </li>
  {% endif %}
    {# Pages #}
  {% if pageCount < 12 %}{# less than 12 Pages #}
    {% for i in 1..pageCount %}
        <li {% if startPage == i %}class="active"{% endif %}><a href="{{ path(app.request.attributes.get('_route'), {'page': i}) }} ">{{i}}</a></li>
    {% endfor %}
    {% else %}
      {% if startPage < 8 %}{# any current page before 7 #}
      {# Pages #}
      {% for i in 1..8 %}
          <li {% if startPage == i %}class="active"{% endif %}><a href="{{ path(app.request.attributes.get('_route'), {'page': i}) }} ">{{i}}</a></li>
      {% endfor %}
      <li class="disabled"><a href="#">...</a></li>
      <li><a href="{{ path(app.request.attributes.get('_route'), {'page': pageCount - 1}) }} ">{{pageCount - 1}}</a></li>
      <li><a href="{{ path(app.request.attributes.get('_route'), {'page': pageCount}) }} ">{{pageCount}}</a></li>
      {% else %}
        {% if startPage > pageCount - 7 %}{# any current page in the last 7 #}
          {# Pages #}
          <li><a href="{{ path(app.request.attributes.get('_route'), {'page': 1}) }} ">1</a></li>
          <li><a href="{{ path(app.request.attributes.get('_route'), {'page': 2}) }} ">2</a></li>
          <li class="disabled"><a href="#">...</a></li>
          {% for i in 7..0 %}
              <li {% if startPage == pageCount - i %}class="active"{% endif %}><a href="{{ path(app.request.attributes.get('_route'), {'page': pageCount - i}) }} ">{{pageCount - i}}</a></li>
          {% endfor %}
          {% else %}{# any other Page #}
            <li><a href="{{ path(app.request.attributes.get('_route'), {'page': 1}) }} ">1</a></li>
            <li><a href="{{ path(app.request.attributes.get('_route'), {'page': 2}) }} ">2</a></li>
            <li class="disabled"><a href="#">...</a></li>
            <li><a href="{{ path(app.request.attributes.get('_route'), {'page': startPage - 2}) }} ">{{startPage - 2}}</a></li>
            <li><a href="{{ path(app.request.attributes.get('_route'), {'page': startPage - 1}) }} ">{{startPage - 1}}</a></li>
            <li class="active"><a href="{{ path(app.request.attributes.get('_route'), {'page': startPage}) }} ">{{startPage}}</a></li>
            <li><a href="{{ path(app.request.attributes.get('_route'), {'page': startPage + 1}) }} ">{{startPage + 1}}</a></li>
            <li><a href="{{ path(app.request.attributes.get('_route'), {'page': startPage + 2}) }} ">{{startPage + 2}}</a></li>
            <li class="disabled"><a href="#">...</a></li>
            <li><a href="{{ path(app.request.attributes.get('_route'), {'page': pageCount - 1}) }} ">{{pageCount - 1}}</a></li>
            <li><a href="{{ path(app.request.attributes.get('_route'), {'page': pageCount}) }} ">{{pageCount}}</a></li>
          {% endif %}{# any current page in the last 7 #}
        {% endif %}{# any current page before 8 #}
      {% endif %}{# less than 12 Pages #}
  {# Next #}
  {% if startPage == pageCount %}
    <li class="disabled">
      <a href="#" aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
      </a>
    </li>
  {% else %}
    <li>
      <a href="{{ path(app.request.attributes.get('_route'), {'page': startPage + 1}) }} " aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
      </a>
    </li>
  {% endif %}
</ul>
</nav>

**更新包括@ste 的帮助** 编辑控制器:

 * @Route("/document/edit/{id}/{page}", name="documentBundle_edit", requirements={"id" = "\d+", "page" = "\d+"}, defaults={"page" = 1})
        * @Template()
        */

        public function editAction(Request $request, $id, $page) {
$em = $this->getDoctrine()->getManager();
      $document = $em->getRepository('DocumentBundle:Document')->findOneByIdInContext($id, $currentuser);
      $allComments = $document->getComments();
      $docAgencies = $document->getAgencies();
    /*
        * CREATE PAGINATION FOR TABLES
        */
        /**
        * @var $paginator \Knp\Component\Pager\Paginator
        */
        $paginator = $this->get('knp_paginator');
        $agencyTable = $paginator->paginate(
          $docAgencies,
          $page,
          5
        );
        $agencyTable->setTemplate('DocumentBundle::table_pagination.html.twig');
        $commentTable = $paginator->paginate(
          $allComments,
          $page,
          5
        );
        $commentTable->setTemplate('DocumentBundle::table_pagination.html.twig');
  return $this->render('DocumentBundle:Document:edit.html.twig', Array(
          'document' => $document,
          'docAgencies' => $agencyTable,
          'comments' => $commentTable,
          'form' => $form->createView(),
        ));
}

分页模板

{# Pagination to be included anywhere. Needs {page, pageCount} #}
<nav>
<ul class="pagination">
  {# Previous #}
  {% if startPage == 1 %}
    <li class="disabled">
      <a href="#" aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
      </a>
    </li>
  {% else %}
    <li>
      <a href="{{ path(route, query|merge({'page': startPage - 1})) }} " aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
      </a>
    </li>
  {% endif %}
    {# Pages #}
  {% if pageCount < 12 %}{# less than 12 Pages #}
    {% for i in 1..pageCount %}
        <li {% if startPage == i %}class="active"{% endif %}><a href="{{ path(route, query|merge({'page': i})) }} ">{{i}}</a></li>
    {% endfor %}
    {% else %}
      {% if startPage < 8 %}{# any current page before 7 #}
      {# Pages #}
      {% for i in 1..8 %}
          <li {% if startPage == i %}class="active"{% endif %}><a href="{{ path(route, query|merge({'page': i})) }}">{{i}}</a></li>
      {% endfor %}
      <li class="disabled"><a href="#">...</a></li>
      <li><a href="{{ path(route, query|merge({'page': pageCount - 1})) }}">{{pageCount - 1}}</a></li>
      <li><a href="{{ path(route, query|merge({'page': pageCount})) }}">{{pageCount}}</a></li>
      {% else %}
        {% if startPage > pageCount - 7 %}{# any current page in the last 7 #}
          {# Pages #}
          <li><a href="{{ path(route, query|merge({'page': 1})) }} ">1</a></li>
          <li><a href="{{ path(route, query|merge({'page': 2})) }} ">2</a></li>
          <li class="disabled"><a href="#">...</a></li>
          {% for i in 7..0 %}
              <li {% if startPage == pageCount - i %}class="active"{% endif %}><a href="{{ path(route, query|merge({'page': pageCount - i})) }} ">{{pageCount - i}}</a></li>
          {% endfor %}
          {% else %}{# any other Page #}
            <li><a href="{{ path(route, query|merge({'page': 1})) }}">1</a></li>
            <li><a href="{{ path(route, query|merge({'page': 2})) }}">2</a></li>
            <li class="disabled"><a href="#">...</a></li>
            <li><a href="{{ path(route, query|merge({'page': startPage - 2})) }} ">{{startPage - 2}}</a></li>
            <li><a href="{{ path(route, query|merge({'page': startPage - 1})) }} ">{{startPage - 1}}</a></li>
            <li class="active"><a href="{{ path(route, query|merge({'page': startPage})) }} ">{{startPage}}</a></li>
            <li><a href="{{ path(route, query|merge({'page': startPage + 1})) }}">{{startPage + 1}}</a></li>
            <li><a href="{{ path(route, query|merge({'page': startPage + 2})) }} ">{{startPage + 2}}</a></li>
            <li class="disabled"><a href="#">...</a></li>
            <li><a href="{{ path(route, query|merge({'page': pageCount - 1})) }} ">{{pageCount - 1}}</a></li>
            <li><a href="{{ path(route, query|merge({'page': pageCount})) }} ">{{pageCount}}</a></li>
          {% endif %}{# any current page in the last 7 #}
        {% endif %}{# any current page before 8 #}
      {% endif %}{# less than 12 Pages #}
  {# Next #}
  {% if startPage == pageCount %}
    <li class="disabled">
      <a href="#" aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
      </a>
    </li>
  {% else %}
    <li>
      <a href="{{ path(route, query|merge({'page': startPage + 1})) }} " aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
      </a>
    </li>
  {% endif %}
</ul>
</nav>

这就是我将分页添加到模板的方式:

{{ knp_pagination_render(docAgencies) }}

看来您在 table_pagination.html.twig 中遇到了问题。

你应该替换这个:

{{ path(app.request.attributes.get('_route'), {'page': THE_PAGE_YOU_HAVE}) }}

有了这个:

{{ path(route, query|merge({'pag': THE_PAGE_YOU_HAVE})) }}

或这个

{{ path(app.request.attributes.get('_route'), app.request.query.all|merge({'pag': THE_PAGE_YOU_HAVE})) }}

如果有效请告诉我。

此外,您应该在 editAction

的路由中删除 id 的默认值