uvoelkel/serverside-datatables-bundle

DataTables 集成到 Symfony

5.0.0 2022-02-15 08:07 UTC

This package is not auto-updated.

Last update: 2024-09-24 15:32:30 UTC


README

Build Status

它做什么

The DataTablesBundle 允许您轻松地创建(可排序和可筛选)从 Doctrine 实体生成的 服务器端 DataTables

许可证

此包采用 MIT 许可证。请参阅包中的完整许可证

LICENSE

安装

通过在您的项目中的 app/AppKernel.php 文件中添加以下行来启用此包

# app/AppKernel.php

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...

            new Voelkel\DataTablesBundle\VoelkelDataTablesBundle(),
        );

        // ...
    }

    // ...
}

配置

安装包后,请确保将此路由添加到您的路由中

# app/config/routing.yml
datatables:
    resource: "@VoelkelDataTablesBundle/Resources/config/routing.xml"

本地化

# app/config/config.yml
voelkel_data_tables:
    localization:
        locale: "%locale%"
        data:
            true: "Jepp"
            false: "Nope"
            datetime: "Y-m-d H:i:s"

用法

创建表格定义

# AppBundle/DataTable/CustomerTable.php

<?php

namespace AppBundle\DataTable;

use Voelkel\DataTablesBundle\Table\AbstractDataTable;
use Voelkel\DataTablesBundle\Table\TableBuilderInterface;
use Voelkel\DataTablesBundle\Table\TableOptions;
use Voelkel\DataTablesBundle\Table\TableSettings;
use Voelkel\DataTablesBundle\Table\Column\Column;
use Voelkel\DataTablesBundle\Table\Column\UnboundColumn;
use Voelkel\DataTablesBundle\Table\Column\CallbackColumn;
use Voelkel\DataTablesBundle\Table\Column\EntityColumn;
use Voelkel\DataTablesBundle\Table\Column\EntitiesColumn;    

class CustomerTable extends AbstractDataTable
{
    protected function configure(TableSettings $settings, TableOptions $options)
    {
        $settings->setName('customer');
        $settings->setEntity('App\Entity\Customer');

        $options['stateSave'] = true;
    }

    protected function build(TableBuilderInterface $builder)
    {
        $builder
            ->add('id')
            ->add('firstname')
            ->add('lastname', Column::class, [
                'label' => 'Lastname'
            ])
            ->add('opening', UnboundColumn::class, [
                'callback' => function(Customer $customer) {
                    return 'Dear ' . ('f' === $customer->getGender() ? 'Madam' : 'Sir');
                }
            ])
            ->add('status', CallbackColumn::class, [
                'callback' => function($status) {
                    switch ($status) {
                        case 1:
                            return 'something';
                            break;
                        case 2:
                            return 'something else';
                            break;
                        default:
                            return 'invalid';
                            break;
                }
            ])
            ->add('group.name'))                                                    // customer has one group
            ->addColumn(new EntityColumn('state', 'city.state', 'name'))            // customer has one city. city has one state
            ->addColumn(new EntitiesColumn('orders', 'orders', 'number'))           // customer has many orders
            ->addColumn(new EntitiesCountColumn('addresses_count', 'addresses'))    // customer has many addresses
            ->addColumn('actions', ActionsColumn::class, [
                'actions' => [
                    'edit' => [
                        'title' => 'edit customer',
                        'label' => '<i class="fa fa-edit"></i>',
                        'callback' => function(Customer $customer, \Symfony\Component\Routing\RouterInterface $router) {
                            return $router->generate('customer_edit', ['id' => $customer->getId()]);
                        },
                    ],
                ],
                'dropdown' => true,
                'dropdown_label' => 'Actions',
            ])
        ;
    }
}

在您的 CustomerController 中

# AppBundle/Controller/CustomerController.php

use AppBundle\DataTable\CustomerTable;

class CustomerController extends Controller 
{
    public function indexAction()
    {
        return $this->render('AppBundle:Customer:index.html.twig', [
            'table' => new CustomerTable(),
        ]);
    }
}

并在您的 index 模板中

# AppBundle/Resources/views/Customer/index.html.twig

{% extends '::base.html.twig' %}

{% block body %}
    {{ datatables_html(table) }}
{% endblock %}

{% block javascripts %}
    <script>
        {{ datatables_js(table) }}

        // access the table instance
        {{ table.name }}_table.on('dblclick', 'tbody tr', function () {
            alert('dblclick');
        });
    </script>
{% endblock %}

访问 DI 容器

use Voelkel\DataTablesBundle\Table\AbstractDataTable;

class CustomerTable extends AbstractDataTable
{
    protected function build()
    {
        $service = $this->container->get('service');
        // or short
        $service = $this->get('service');

        // ...
        ->addColumn(new Column('id', 'id', [
            'format_data_callback' => function($data, $object, Column $column) {
                $router = $this->container->get('router');
                // or
                $router = $this->get('router');
            },
        ]))
        // ...
    }
}

将表格定义作为服务

定义服务

# AppBundle/Resources/config/services.xml

<service id="app.table.customer" class="AppBundle\DataTable\CustomerTable">
    <argument type="service" id="my.awesome.service" />
</service>

在表格构造函数中设置服务 ID

# AppBundle/DataTable/CustomerTable.php

private $myAwesomeService;

public function __construct($myAwesomeService)
{
    $this->myAwesomeService = $myAwesomeService;
}

protected function configure(TableSettings $settings, TableOptions $options)
{
    $settings->setName('customer');
    $settings->setEntity('AppBundle\Entity\Customer');
    $settings->setServiceId('app.table.customer');
}

在您的控制器中

# AppBundle/Controller/CustomerController.php

public function indexAction()
{
    return $this->render('AppBundle:Customer:index.html.twig', [
        'table' => $this->get('app.table.customer'),
    ]);
}

列筛选器

# AppBundle/DataTable/CustomerTable.php

// ...

class CustomerTable extends AbstractDataTable
{
    // ...
    protected function build()
    {
        $this
            // ...
            ->add('gender', Column:class, [
                'filter' => 'select',
                'filter_choices' => [
                    'm' => 'male',
                    'f' => 'female',
                ],
            ])
            ->add('lastname', Column::class, [
                'filter' => 'text',
            ])
        ;
    }
}

表格选项

$default = [
    'stateSave' => false,
    'stateDuration' => 7200,
];
  • 'stateDuration': -1 sessionStorage. 0 或更大 localStorage. 0 无限。 > 0 持续时间(秒)
class CustomerTable extends AbstractTableDefinition
{
    // ...
    protected function configure(TableSettings $settings, TableOptions $options)
    {
        $options['stateSave'] = true;
        $options['stateDuration'] = 120;
    }
}

列选项

$default = [
    'sortable' => true,
    'searchable' => true,
    'filter' => false, // false|'text'|'select'
    'filter_choices' => [],
    'filter_empty' => false, // add a checkbox to filter empty resp. null values
    'multiple' => false,
    'expanded' => false,
    'format_data_callback' => null, // function ($data, $object, Column $column) {}
    'unbound' => false,
    'order' => null, // null|'asc'|'desc'
    'label' => null, // null|string|false
    'abbr' => null, // null|string
];
  • 'filter' != false implies 'searchable' = true
  • 'multiple' has no effect if filter != 'select'
  • 'expanded' has no effect if filter != 'select'