arturdoruch/list-bundle

Symfony 包,用于列表项的分页、排序和过滤。

安装: 180

依赖者: 0

建议者: 0

安全: 0

星级: 1

关注者: 1

分支: 0

开放问题: 0

类型:symfony-bundle

0.2.3 2021-07-11 01:34 UTC

This package is auto-updated.

Last update: 2024-09-11 08:27:56 UTC


README

Symfony 包,用于列表项的分页、排序和过滤。

包包含支持以下分页器的分页器:

  • 数组
  • Doctrine\ORM\Query
  • Doctrine\ORM\QueryBuilder
  • Doctrine\ODM\MongoDB\Query\Query
  • Doctrine\ODM\MongoDB\Query\Builder
  • Doctrine\MongoDB\CursorInterface
  • MongoCursor

对于其他数据库查询或游标,您可以创建自己的分页器。请参阅 分页器配置选项

安装

运行 composer 命令

composer require arturdoruch/list-bundle

并在应用程序 Kernel 类中注册 list-bundle 和其他必需的包。

Symfony 3 中

// app/AppKernel.php
public function registerBundles()
{
    $bundles = [
        // Other bundles
        new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
        new Symfony\Bundle\TwigBundle\TwigBundle(),
        new ArturDoruch\ListBundle\ArturDoruchListBundle(),
    ];
}    

Symfony >= 4 中

// config/bundles.php
return [
    // Other bundles
    Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
    Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
    ArturDoruch\ListBundle\ArturDoruchListBundle::class => ['all' => true],
];

JavaScript 支持

要启用 JavaScript 支持,请使用 yarnnpm 安装包 @arturdoruch/list。该包还包含一个包含 CSS 样式的文件,用于美化筛选表单和项目列表。

包配置

请参阅 包配置选项

用法

简要概述

  1. 创建获取项目列表的控制器动作
  2. 创建显示项目列表的模板

控制器

创建获取项目列表的控制器动作

控制器动作的要求

  • 路由方法必须是类型 GET
  • 必须将 ArturDoruch\ListBundle\ItemList 对象传递给 twig 模板。

获取书籍列表的控制器动作的完整示例

<?php

namespace AppBundle\Controller;

use AppBundle\Form\Type\BookFilterType;
use ArturDoruch\ListBundle\ItemList;
use ArturDoruch\ListBundle\Paginator;
use ArturDoruch\ListBundle\Request\QueryParameterBag;
use ArturDoruch\ListBundle\Sorting\SortChoiceCollection;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class BookController
{
    /**
     * @Route(
     *     "/",
     *     methods={"GET"}
     * )
     * @Template("@App/book/list.html.twig")
     */
    public function list(Request $request)
    {
        // (optional) Create filter form.
        // Info: 
        // The request URL query parameter name with filtering parameters, is created based on the form name.
        // Because of that use Symfony\Component\Form\FormFactory::createNamed() method
        // for creating form with own name (e.g. "filter").
        $form = $this->get('form.factory')->createNamed('filter', BookFilterType::class);
        $form->handleRequest($request);

        // Filtering criteria.
        $criteria = [];

        if ($form->isSubmitted() && $form->isValid()) {
            $criteria = $form->getData();
        }
               
        // Get request query parameters (page, limit, sort).
        $parameterBag = new QueryParameterBag($request);        
        // Array with sorting field and order, pair ["field" => "order"]
        $sort = $parameterBag->getSort();
        
        // Get book items - array, query or cursor depend on database type.
        $bookRepository = '';
        $books = $bookRepository->get($criteria, $sort);        
        
        $pagination = Paginator::paginate($books, $parameterBag->getPage(), $parameterBag->getLimit(100));
        // (optional) Set item limits (overrides values form default config "pagination.item_limits").
        $pagination->setItemLimits([50, 100, 200]);

        // (optional) Define SortChoiceCollection to display "select" field with sorting options.
        // Alternatively you can render sorting links in twig template with "arturdoruch_list_sort_link" function.
        $sortChoiceCollection = new SortChoiceCollection();
        $sortChoiceCollection
            ->add('Lowest price', 'price', 'asc') // Sort books by price ascending.
            ->add('Highest price', 'price', 'desc'); // Sort books by price descending.

        return [
            'bookList' => new ItemList($pagination, $form, $sortChoiceCollection),
        ];
    }
}

分页项限制

每页显示的列表项的默认限制在包配置中指定,路径为 pagination.item_limits。要为特定列表设置不同的项限制,请调用 ArturDoruch\ListBundle\Pagination::setItemLimits() 方法并传递自定义值。

示例

<?php

use ArturDoruch\ListBundle\Paginator;

// In controller
$pagination = Paginator::paginate($items, $page, $limit);
$pagination->setItemLimits([50, 100, 200]);

筛选表单

为了过滤列表项,您必须创建 FormType 类。

  • 您可以使用 ArturDoruch\ListBundle\Form\FilterType 类并在控制器中添加自定义筛选字段,
  • 或创建自己的表单类型类,并(可选地)扩展 ArturDoruch\ListBundle\Form\FilterType 类。

筛选表单必须具有类型为 GET 的方法和将 csrf_protection 选项设置为 false。
将创建的 FormType 类传递给 ArturDoruch\ListBundle\ItemList 对象的构造函数。

筛选表单类型类的示例

<?php

namespace AppBundle\Form\Type;

use AppBundle\Entity\BookCategory;
use ArturDoruch\ListBundle\Form\FilterType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

class BookFilterType extends FilterType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder
            ->add('category', EntityType::class, [
                'placeholder' => '-- all --',
                'class' => BookCategory::class,
                'choice_label' => 'category',
                'choice_value' => 'id'
            ])
            ->add('author')
            ->add('title');
    }
}

排序选择集合

如果您想渲染一个具有排序选项的 HTML "select" 字段,请创建 ArturDoruch\ListBundle\Sorting\SortChoiceCollection 对象并指定排序选项。然后,将 SortChoiceCollection 对象传递给 ArturDoruch\ListBundle\ItemList 对象的构造函数。

这是在 twig 模板中使用 arturdoruch_list_sort_link 函数渲染排序链接的替代方案。

示例

<?php

use ArturDoruch\ListBundle\ItemList;
use ArturDoruch\ListBundle\Sorting\SortChoiceCollection;

// In controller action.
$sortChoiceCollection = new SortChoiceCollection();
$sortChoiceCollection
    ->add('Cheapest first', 'price', 'asc') // Sort books by price ascending.
    ->add('Expensive first', 'price', 'desc'); // Sort books by price descending.
    
new ItemList($pagination, $form, $sortChoiceCollection); 

视图

Twig 函数

请参阅 Twig 函数 渲染列表组件。

创建显示项目列表的模板

{# base.html.twig #}
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        {% block content %}
        {% endblock %}
    </body>
</html>

用于 AJAX 请求的模板

{# ajax_list.html.twig #}
{% block list %}{% endblock %}

显示所有列表组件的模板示例。

{# book/list.html.twig #}
{# Update only list table (block list) when is AJAX request. #}
{% extends app.request.xmlHttpRequest ?
    '@App/ajax_list.html.twig':
    '@App/base.html.twig'
%}

{% block content %}
    {{ arturdoruch_list_filter_form(bookList.filterForm) }}

    <div id="book-list-container">
    {% block list %}
        {% if bookList.count > 0 %}
        {{ arturdoruch_list_items_and_pagination(bookList.pagination) }}
        {{ arturdoruch_list_sort_form(bookList.sortChoiceCollection) }}

        <table class="table" id="book-list">
            <thead>
                <tr>
                    <th>Category</th>
                    <th>{{ arturdoruch_list_sort_link('Author', 'author') }}</th>
                    <th>{{ arturdoruch_list_sort_link('Title', 'title') }}</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>
            {% for book in bookList %}
                <tr>
                    <td>{{ book.category }}</td>
                    <td>{{ book.author }}</td>>
                    <td>{{ book.title }}</td>
                    <td>{{ book.price }}</td>                                      
                </tr>
            {% endfor %}
            </tbody>
        </table>
        {% else %}
            <h4>No books with the specified criteria.</h4>
        {% endif %}
    {% endblock %}
    </div>
{% endblock %}