使用KnpPaginatorBundle在symfony 4中进行分页

时间:2018-08-19 19:26:24

标签: symfony symfony-forms symfony-2.1 symfony4

试图从名称空间“ KnpPaginatorBundle”中加载类“ App\Knp\Bundle\PaginatorBundle”。您是否忘记了“ use的“ Knp\Bundle\PaginatorBundle\KnpPaginatorBundle”声明?

controller image

kernel image

services image

index image

3 个答案:

答案 0 :(得分:0)

只需添加KnpPaginatorBundle的类命名空间:

config/bundles.php中:

<?php

return [
    Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
    Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
    ***************************************************************
    ***************************************************************
    Knp\Bundle\PaginatorBundle\KnpPaginatorBundle::class => ['all' => true]
];

答案 1 :(得分:0)

您忘了将Bundle完全添加到config/bundles.php

Knp\Bundle\PaginatorBundle\KnpPaginatorBundle::class => ['all' => true]

答案 2 :(得分:0)

解决方案是创建一个新的存档paginator.yaml

//config/paginator.yaml
knp_paginator:
  page_range: 5                      # rango por defecto de paginas en los controles del paginador
  default_options:
    page_name: page                # nombre del parámetro de la URL para la página
    sort_field_name: sort          # nombre del parámetro de la URL para la ordenación
    sort_direction_name: direction # nombre del parámetro de la URL para la dirección(ASC o DESC)
    distinct: true                 # Garantizar resultados distintos
  template:
    pagination: '@KnpPaginator/Pagination/sliding.html.twig'  # plantilla controles
    sortable: KnpPaginatorBundle:Pagination:sortable_link.html.twig # plantilla links ordenación

在Controller中之后,在类中添加extends Controller

<?php

namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Usuario;
use App\Form\UsuarioType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

/**
 * @Route("/admin/usuarios")
 */
class BackendController extends Controller
{
    /**
     * @Route("/", name="admin")
     */
    public function index(Request $request)
    {
        $usuarios = $this->getDoctrine()
            ->getRepository(Usuario::class)
            ->findAll();
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
            $usuarios, $request->query->getInt('page', 1), 20);

        return $this->render('backend/usuario/index.html.twig',
            array('pagination' => $pagination));

    }

最后将其添加到archive.yml

<div class="navigation">
  {{ knp_pagination_render(pagination) }}
</div>

参考:https://github.com/KnpLabs/KnpPaginatorBundle/issues/468#issuecomment-356580135