pagination in symfony 4 using KnpPaginatorBundle

余生颓废 提交于 2019-12-06 15:19:43

Just add class namespace of KnpPaginatorBundle:

in 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]
];

You forgot to add your Bundle in the Kernel , exactly in config/bundles.php

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

The solution is create a new archive 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

After in the Controller add extends Controller in the class

<?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));

    }

Finally add this in the archive.yml

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!