定制 steelants/datatable 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

steelants/datatable

Composer 安装命令:

composer require steelants/datatable

包简介

Simple Datatable class based on Laravel and livewire

README 文档

README

Created by: SteelAnts s.r.o.

Total Downloads

Docker Build

  • is handeled by gittea server
  git checkout master
  git pull origin master
  git pull origin dev
  git tag 2.3.2
  git push --tags
  git checkout dev

Usage

namespace App\Livewire;

use App\Models\User;
use SteelAnts\DataTable\Livewire\DataTableComponent;
use Illuminate\Database\Eloquent\Builder;
use SteelAnts\DataTable\Traits\UseDatabase;

class UserTable extends DataTableComponent
{
    Use UseDatabase;
	// or UseDatabaseEloquent, if you want to receive model instead ov serialized array

    // Get model query
    public function query(): Builder
    {
        return User::query();
    }

    // Set headers
    public function headers(): array
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'email' => 'E-mail',
        ];
    }

    // Set actions
    public function actions($item) : array
    {
        return [
            [
                // livewire action
                'type' => "livewire",
                'action' => "remove",
                'parameters' => $item['id'],
                'text' => "Remove",
                'actionClass' => 'text-danger',
                'iconClass' => 'fas fa-trash',
                'confirm' => 'Are you sure you want to delete this post?',
            ],
            [
                // url action
                'type' => "url",
                'url' => rounte('user.show', [id => $item['id']]),
                'text' => "Show",
                'iconClass' => 'fas fa-eye',
            ]
        ];
    }

    // Custom render of 'name' column
    public function renderColumnName($value, $row){
        return '<b>'.e($value).'</b>';
    }

    // Transform order column on raw order column (optional)
    public function orderColumnName(){
         return 'CAST(name AS STRING)';
    }

    // Livewire actions
    public function remove($id){
        User::find($id)->delete();
    }
}

Using without query / models

    // instead of method query() implement dataset()
    public function dataset(): array
    {
        return [
            [
                'id' => '1',
                'name' => 'Name 1',
                'email' => 'E-mail 1',
            ],
            [
                'id' => '2',
                'name' => 'Name 2',
                'email' => 'E-mail 2',
            ],
            // ...
        ];
    }

Render

@livewire('user-table', [], key('data-table'))

Dev Enviroment

  1. Clone Repo to [LARVEL-ROOT]/packages/
  2. Modify ;composer.json`
    "autoload": {
        "psr-4": {
            ...
            "SteelAnts\\DataTable\\": "packages/Livewire-DataTable/src/"
            ...
        }
    },
  1. Add (code below) to: [LARVEL-ROOT]/bootstrap/providers.php
SteelAnts\DataTable\DataTableServiceProvider::class,

Sorting

Sorting is enabled by default. Set $sortable = true and optionally restrict which columns are sortable via $sortableColumns.

Simple columns

Sorting by any direct column (string, int, bool) works out of the box:

public bool $sortable = true;
public array $sortableColumns = ['name', 'score', 'published'];

BelongsTo relation

Use dot notation — the package resolves the join automatically:

// headers
'user.name' => 'User'

// sortBy
$sortBy = 'user.name';

HasMany / MorphMany — sort by count

Same dot notation. The package detects the relation type and generates a COUNT subquery:

// headers
'comments.id' => 'Comments'  // sorts by number of comments
'reactions.id' => 'Reactions' // sorts by number of reactions (morph-aware)

// sortBy
$sortBy = 'comments.id';

Custom sort expression

Override orderColumn{Name}() to return a raw SQL expression:

public function orderColumnName(): string
{
    return 'LOWER(name)';
}

Testing

The package uses Pest with Orchestra Testbench and an in-memory SQLite database.

Install dev dependencies:

composer install

Run all tests:

./vendor/bin/pest

Run only sorting tests:

./vendor/bin/pest tests/Feature/SortingTest.php

Configuration

// Enable sorting
public bool $sortable = true;

// Enable pagination
public bool $paginated = true;

// Enable fulltext search
public bool $searchable = true;
public bool $searchableColumns = [];

//Enable filters
public bool $filterable = true;

Render casts

New preferred way to customize render.

// Define cast by header key
public function renderCasts(): array
{
	return [
		'is_active' => BoolAsIcon::class,
	];
}

Example render cast

use SteelAnts\DataTable\RenderCasts\RenderCast;

class BoolAsIcon implements RenderCast
{
    public function render($key, $value, $model)
    {
        return '<i class="' . ($value ? 'far fa-check-circle text-success' : 'far fa-times-circle text-danger') . '"></i>';
    }
}

Optional transforms methods

Original render customization.

// Transformace whole row on input (optional)
// Returns associative array
public function row(Model $row) : array
{
    return [
        'id' => $row->id,
    ];
}

// Transform one column on input (optional)
public function columnFoo(mixed $column) : mixed
{
    return $column;
}


// Transform whole row on output (optional)
// !!! NOTE: values are rendered with {!! !!}, manually escape values
public function renderRow(array $row) : array
{
    return [
        'id' => e($row['id'])
    ];
}

// Transform one column on output (optional)
// !!! NOTE: values are rendered with {!! !!}, manually escape values
public function renderColumnFoo(mixed $value, array $row) : string
{
    return e($value);
}

Filters methods

    //Add filters to header for specific columns
    public function headerFilters(): array
    {
        return [
            'column1Key' => ['type' => 'text'], //input type
            'column2Key' => ['type' => 'select', 'values' => ['value' => 'name', 'value2' => 'name2']], //this for select
            'column3Key' => ['type' => 'date'], //double input type (date,time,datetime-local)
        ];
    }

    //Add actions to header filters edit
    public function updatedHeaderFilter(){
        $this->validate([
            'headerFilter.column1Key' => 'nullable|string',
            'headerFilter.column2Key' => 'nullable|string',
            'headerFilter.column3Key.*' => 'nullable|date', //have two parameters "from" and "to"
        ]);
    }

Development

  1. Create subfolder /packages at root of your laravel project

  2. clone repository to sub folder /packages (you need to be positioned at root of your laravel project in your terminal)

git clone https://github.com/steelants/Livewire-DataTable.git ./packages/Livewire-DataTable
  1. edit composer.json file
"autoload": {
	"psr-4": {
		"SteelAnts\\Modal\\": "packages/Livewire-Modal/src/"
	}
}
  1. Add provider to bootstrap/providers.php
return [
	...
     SteelAnts\DataTable\DataTableServiceProvider::class,
	...
];

Contributors

Other Packages

steelants/laravel-auth

steelants/laravel-boilerplate

steelants/datatable

steelants/form

steelants/modal

steelants/laravel-tenant

steelants/datatable 适用场景与选型建议

steelants/datatable 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.89k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2023 年 06 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 steelants/datatable 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 steelants/datatable 我们能提供哪些服务?
定制开发 / 二次开发

基于 steelants/datatable 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 4.89k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 3
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-06-23