KnpPaginatorBundle-默认顺序

时间:2019-12-02 16:00:34

标签: symfony knppaginator knppaginatorbundle

我试图在查询后使KnpPaginatorBundle默认为“ order by”。

我尝试了以下方法,但没有任何运气!

[
    'defaultSortFieldName'      => 'i.name',
    'defaultSortDirection'      => 'desc'
]

之所以这样做,是因为我的下一个可排序选项不需要按名称排序,因此不想在查询中包括排序依据。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我相信KnpPaginatorBundle将改变并与您的$ _GET全局变量一起玩,这并不理想。我发现更好的选择是控制自己的排序。

一个最小的例子:

<?php

namespace App\Repository;

use App\Entity\Blog;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Doctrine\ORM\Query\Expr;

/**
 * @method Blog|null find($id, $lockMode = null, $lockVersion = null)
 * @method Blog|null findOneBy(array $criteria, array $orderBy = null)
 * @method Blog[]    findAll()
 * @method Blog[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class BlogRepository extends ServiceEntityRepository
{
    private const LIMIT_BLOGS_PER_PAGE = 20;
    private $paginator;

    public function __construct(RegistryInterface $registry, PaginatorInterface $paginator)
    {
        $this->paginator = $paginator;
        parent::__construct($registry, Blog::class);
    }

    public function getPaginatedBlogs(int $page, array $params = [], bool $isPublished = true)
    {
        list($sortKey, $order) = $this->getSorting(@$params['sort']);

        $qb = $this->createQueryBuilder('blog')
            ->where('blog.is_published = :is_published')
            ->setParameter('is_published', $isPublished);

        // Sort by order as requested by user
        $qb->orderBy($sortKey, $order);

        return $this->paginator->paginate(
            $qb->getQuery(),
            $page,
            self::LIMIT_BLOGS_PER_PAGE,
            []
        );
    }

    private function getSorting($sort)
    {
        switch ($sort) {
            case 'updated':
                $sortKey = 'blog.updated';
                $order = 'DESC';
                break;

            case 'title':
                $sortKey = 'blog.title';
                $order = 'ASC';
                break;

            default:
                $sortKey = 'blog.created';
                $order = 'DESC';
                break;
        }

        return [$sortKey, $order];
    }
}