thephpguys/spiral-datagrid-bundle

安装: 0

依赖: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 0

公开问题: 0

类型:symfony-bundle

v0.0.1 2024-07-25 08:27 UTC

This package is auto-updated.

Last update: 2024-09-25 08:55:39 UTC


README

此包为您的 Symfony 项目提供了与 spiral/data-grid 的集成。受 spiral/data-grid-bridge 包的启发,它提供了以下功能

  • 将 DataGrid 组件无缝集成到 Symfony 环境中
  • Doctrine\ORM\QueryBuilder writer,用于根据过滤器构建 DQL。
  • 控制器 DataGrid 属性

DataGrid 组件文档

安装

确保全局已安装 Composer,如 Composer 文档的 安装章节 所述。

使用 Symfony Flex 的应用程序

打开命令行,进入您的项目目录,执行以下命令

composer require thephpguys/spiral-datagrid-bundle

不使用 Symfony Flex 的应用程序

步骤 1:下载包

打开命令行,进入您的项目目录,并执行以下命令以下载此包的最新稳定版本

composer require thephpguys/spiral-datagrid-bundle

步骤 2:启用包

然后,通过将其添加到项目 config/bundles.php 文件中注册的包列表中来启用包

// config/bundles.php

return [
    // ...
    ThePhpGuys\SpiralDataGridBundle\SpiralDataGridBundle::class => ['all' => true],
];

使用方法

步骤 1:创建网格模式

通过定义过滤器、排序器和分页设置来创建网格模式。您可以在 DataGrid 文档页面 上找到更多过滤器

namespace App\Grid;
use App\Entity\Product;
use Spiral\DataGrid\GridSchema;
use Spiral\DataGrid\Specification\Filter;
use Spiral\DataGrid\Specification\Pagination\PagePaginator;
use Spiral\DataGrid\Specification\Sorter\Sorter;
use Spiral\DataGrid\Specification\Value\StringValue;

final class ProductGrid extends GridSchema
{

    public function __construct()
    {
        $this->addFilter('search',  new Filter\Any(
            new Filter\Like('e.title'),
            new Filter\Equals('e.article')
        ));
        $this->addSorter('name',new Sorter('e.name'));
        $this->addSorter('article',new Sorter('e.article'));
        $this->setPaginator(new PagePaginator(10, [10, 20, 50, 100]));
    }

    public function withDefaults():array
    {
        return [
            GridFactory::KEY_SORT => ['name'=>'asc']
        ];
    }

    //If this method exists it will be used as response data transformer
    public function __invoke(Product $product):array
    {
        return [
            'id' => $product->getId(),
            'name' => $product->getName(),
            'article' => $product->getArticle(),
        ];
    }
}

步骤 2:将模式注册为服务

config/services.yaml 中将您的网格模式注册为服务

#config/services.yaml

services:
    App\Grid\ProductGrid:

步骤 3:创建控制器方法

创建一个控制器方法来使用 DataGrid

use App\Entity\Product;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Routing\Attribute\Route;
use ThePhpGuys\SpiralDataGridBundle\Attribute\DataGrid

//...
#[Route('/products')]
#[DataGrid(grid: ProductGrid::class)]
public function productsList(EntityManagerInterface $entityManager):QueryBuilder
{
    return $entityManager->createQueryBuilder()->select('*')->from('e',Product::class);
} 
//...

此设置提供具有 JSON 响应以及过滤器、排序器和分页查询参数的路由

示例用法