mcpField
T
tables

tables

github.com/mwguerra开发3688 次安装27 周前更新
代码仓库

关于 tables

tables 是用于生成 FilamentPHP v4 表格配置的技能,面向开发者,依据官方文档模式处理列、筛选器、操作和关联数据。

主要功能

  1. 01配置可搜索和可排序列
  2. 02定义常见字段筛选器
  3. 03添加行、表头和批量操作
  4. 04处理关联数据列
  5. 05生成完整表格配置

适用场景

  1. 01构建支持搜索与排序的管理表格
  2. 02按状态或日期筛选记录
  3. 03添加行操作和批量操作
  4. 04在表格中显示关联记录

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mwguerra/claude-code-plugins --skill tables

安装后在 Claude Code 中输入/tables确认已加载。

详细介绍

FilamentPHP 表格生成技能

概述

此技能会按照官方文档中的模式生成 FilamentPHP v4 表格配置,包括列、筛选器、操作和批量操作。

文档参考

重要: 生成表格之前,请先阅读:

  • /home/mwguerra/projects/mwguerra/claude-code-plugins/filament-specialist/skills/docs/references/tables/
  • /home/mwguerra/projects/mwguerra/claude-code-plugins/filament-specialist/skills/docs/references/tables/02-columns/
  • /home/mwguerra/projects/mwguerra/claude-code-plugins/filament-specialist/skills/docs/references/tables/03-filters/

工作流

第 1 步:分析需求

确定:

  • 要显示的列
  • 可搜索字段
  • 可排序字段
  • 筛选要求
  • 行操作
  • 批量操作
  • 要显示的关联
第 2 步:阅读文档

查看表格文档并提取:

  • 列类名和选项
  • 筛选器配置
  • 操作模式
  • 性能注意事项
第 3 步:生成表格

构建表格配置:

use Filament\Tables;
use Filament\Tables\Table;

public static function table(Table $table): Table
{
    return $table
        ->columns([
            // Columns
        ])
        ->filters([
            // Filters
        ])
        ->actions([
            // Row actions
        ])
        ->bulkActions([
            // Bulk actions
        ]);
}

列类型参考

文本列
// Basic text
Tables\Columns\TextColumn::make('name')
    ->searchable()
    ->sortable();

// With limit and tooltip
Tables\Columns\TextColumn::make('description')
    ->limit(50)
    ->tooltip(fn ($record): string => $record->description);

// Formatted
Tables\Columns\TextColumn::make('price')
    ->money('usd')
    ->sortable();

// Date formatting
Tables\Columns\TextColumn::make('created_at')
    ->dateTime('M j, Y H:i')
    ->sortable()
    ->since();  // Shows "2 hours ago"

// Copyable
Tables\Columns\TextColumn::make('uuid')
    ->copyable()
    ->copyMessage('UUID copied!')
    ->copyMessageDuration(1500);

// With color
Tables\Columns\TextColumn::make('status')
    ->color(fn (string $state): string => match ($state) {
        'draft' => 'gray',
        'reviewing' => 'warning',
        'published' => 'success',
        default => 'gray',
    });

// HTML content
Tables\Columns\TextColumn::make('content')
    ->html()
    ->wrap();

// Word/character count
Tables\Columns\TextColumn::make('bio')
    ->words(10);

// List values (array)
Tables\Columns\TextColumn::make('tags')
    ->listWithLineBreaks()
    ->bulleted();
图标列
// Boolean icon
Tables\Columns\IconColumn::make('is_active')
    ->boolean();

// Custom icons
Tables\Columns\IconColumn::make('status')
    ->icon(fn (string $state): string => match ($state) {
        'draft' => 'heroicon-o-pencil',
        'reviewing' => 'heroicon-o-clock',
        'published' => 'heroicon-o-check-circle',
    })
    ->color(fn (string $state): string => match ($state) {
        'draft' => 'info',
        'reviewing' => 'warning',
        'published' => 'success',
        default => 'gray',
    });
图片列
// Basic image
Tables\Columns\ImageColumn::make('avatar')
    ->circular()
    ->size(40);

// Multiple images (stacked)
Tables\Columns\ImageColumn::make('images')
    ->circular()
    ->stacked()
    ->limit(3)
    ->limitedRemainingText();

// With default
Tables\Columns\ImageColumn::make('logo')
    ->defaultImageUrl(url('/images/default-logo.png'))
    ->square()
    ->size(60);
徽章列
Tables\Columns\BadgeColumn::make('status')
    ->colors([
        'danger' => 'draft',
        'warning' => 'reviewing',
        'success' => 'published',
    ])
    ->icons([
        'heroicon-o-pencil' => 'draft',
        'heroicon-o-clock' => 'reviewing',
        'heroicon-o-check' => 'published',
    ]);

// Or with closure
Tables\Columns\BadgeColumn::make('priority')
    ->color(fn (string $state): string => match ($state) {
        'low' => 'gray',
        'medium' => 'warning',
        'high' => 'danger',
    });
颜色列
Tables\Columns\ColorColumn::make('color')
    ->copyable()
    ->copyMessage('Color code copied');
切换列
// Editable inline toggle
Tables\Columns\ToggleColumn::make('is_active')
    ->onColor('success')
    ->offColor('danger')
    ->afterStateUpdated(fn () => Notification::make()
        ->title('Status updated')
        ->success()
        ->send()
    );
选择列
// Editable inline select
Tables\Columns\SelectColumn::make('status')
    ->options([
        'draft' => 'Draft',
        'published' => 'Published',
    ]);
文本输入列
// Editable inline text
Tables\Columns\TextInputColumn::make('sort_order')
    ->rules(['required', 'numeric']);
复选框列
// Editable inline checkbox
Tables\Columns\CheckboxColumn::make('is_featured');
关联列
// BelongsTo
Tables\Columns\TextColumn::make('author.name')
    ->label('Author')
    ->searchable()
    ->sortable();

// HasMany count
Tables\Columns\TextColumn::make('comments_count')
    ->counts('comments')
    ->label('Comments')
    ->sortable();

// HasMany sum
Tables\Columns\TextColumn::make('items_sum_quantity')
    ->sum('items', 'quantity')
    ->label('Total Quantity');

// BelongsToMany list
Tables\Columns\TextColumn::make('tags.name')
    ->badge()
    ->separator(',');
视图列(自定义)
Tables\Columns\ViewColumn::make('custom')
    ->view('filament.tables.columns.custom-column');

列修饰符

Tables\Columns\TextColumn::make('name')
    // Search
    ->searchable()
    ->searchable(isIndividual: true)

    // Sort
    ->sortable()
    ->sortable(['first_name', 'last_name'])

    // Visibility
    ->toggleable()
    ->toggleable(isToggledHiddenByDefault: true)
    ->visible(fn (): bool => auth()->user()->isAdmin())
    ->hidden(fn ($record): bool => $record->is_private)

    // Sizing
    ->grow(false)
    ->width('200px')
    ->alignCenter()
    ->alignEnd()

    // Styling
    ->weight(FontWeight::Bold)
    ->size(TextColumn\TextColumnSize::Large)
    ->color('primary')
    ->extraAttributes(['class' => 'custom-class']);

筛选器参考

选择筛选器
Tables\Filters\SelectFilter::make('status')
    ->options([
        'draft' => 'Draft',
        'reviewing' => 'Reviewing',
        'published' => 'Published',
    ]);

// Multiple selection
Tables\Filters\SelectFilter::make('status')
    ->multiple()
    ->options([
        'draft' => 'Draft',
        'published' => 'Published',
    ]);

// Relationship filter
Tables\Filters\SelectFilter::make('author')
    ->relationship('author', 'name')
    ->searchable()
    ->preload();
三态筛选器(布尔值)
Tables\Filters\TernaryFilter::make('is_active')
    ->label('Active')
    ->boolean()
    ->trueLabel('Active only')
    ->falseLabel('Inactive only')
    ->native(false);
日期筛选器
Tables\Filters\Filter::make('created_at')
    ->form([
        Forms\Components\DatePicker::make('created_from'),
        Forms\Components\DatePicker::make('created_until'),
    ])
    ->query(function (Builder $query, array $data): Builder {
        return $query
            ->when(
                $data['created_from'],
                fn (Builder $query, $date): Builder => $query->whereDate('created_at', '>=', $date),
            )
            ->when(
                $data['created_until'],
                fn (Builder $query, $date): Builder => $query->whereDate('created_at', '<=', $date),
            );
    })
    ->indicateUsing(function (array $data): array {
        $indicators = [];
        if ($data['created_from'] ?? null) {
            $indicators['created_from'] = 'From ' . Carbon::parse($data['created_from'])->toFormattedDateString();
        }
        if ($data['created_until'] ?? null) {
            $indicators['created_until'] = 'Until ' . Carbon::parse($data['created_until'])->toFormattedDateString();
        }
        return $indicators;
    });
软删除筛选器
Tables\Filters\TrashedFilter::make();
查询构建器筛选器
Tables\Filters\QueryBuilder::make()
    ->constraints([
        Tables\Filters\QueryBuilder\Constraints\TextConstraint::make('name'),
        Tables\Filters\QueryBuilder\Constraints\NumberConstraint::make('price'),
        Tables\Filters\QueryBuilder\Constraints\DateConstraint::make('created_at'),
        Tables\Filters\QueryBuilder\Constraints\RelationshipConstraint::make('author')
            ->icon('heroicon-o-user')
            ->multiple(),
    ]);

操作参考

行操作
->actions([
    Tables\Actions\ViewAction::make(),
    Tables\Actions\EditAction::make(),
    Tables\Actions\DeleteAction::make()
        ->requiresConfirmation(),

    // Custom action
    Tables\Actions\Action::make('publish')
        ->icon('heroicon-o-check')
        ->color('success')
        ->requiresConfirmation()
        ->action(fn (Model $record) => $record->publish())
        ->visible(fn (Model $record): bool => $record->status === 'draft'),

    // Action with modal form
    Tables\Actions\Action::make('send_email')
        ->icon('heroicon-o-envelope')
        ->form([
            Forms\Components\TextInput::make('subject')
                ->required(),
            Forms\Components\RichEditor::make('body')
                ->required(),
        ])
        ->action(function (Model $record, array $data): void {
            Mail::to($record->email)->send(new CustomEmail($data));
        }),

    // Grouped actions
    Tables\Actions\ActionGroup::make([
        Tables\Actions\ViewAction::make(),
        Tables\Actions\EditAction::make(),
        Tables\Actions\DeleteAction::make(),
    ])->dropdown(),

    // Replicate action
    Tables\Actions\ReplicateAction::make()
        ->excludeAttributes(['slug', 'published_at'])
        ->beforeReplicaSaved(function (Model $replica): void {
            $replica->name = $replica->name . ' (Copy)';
        }),
]);
批量操作
->bulkActions([
    Tables\Actions\BulkActionGroup::make([
        Tables\Actions\DeleteBulkAction::make(),
        Tables\Actions\ForceDeleteBulkAction::make(),
        Tables\Actions\RestoreBulkAction::make(),

        // Custom bulk action
        Tables\Actions\BulkAction::make('publish')
            ->icon('heroicon-o-check')
            ->requiresConfirmation()
            ->action(fn (Collection $records) => $records->each->publish())
            ->deselectRecordsAfterCompletion(),

        // Export bulk action
        Tables\Actions\BulkAction::make('export')
            ->icon('heroicon-o-arrow-down-tray')
            ->action(fn (Collection $records) => static::export($records)),
    ]),
]);
表头操作
->headerActions([
    Tables\Actions\CreateAction::make(),
    Tables\Actions\AttachAction::make()
        ->preloadRecordSelect(),

    // Import action
    Tables\Actions\Action::make('import')
        ->icon('heroicon-o-arrow-up-tray')
        ->form([
            Forms\Components\FileUpload::make('file')
                ->acceptedFileTypes(['text/csv']),
        ])
        ->action(fn (array $data) => static::import($data['file'])),
]);

表格配置

public static function table(Table $table): Table
{
    return $table
        ->columns([...])
        ->filters([...])
        ->actions([...])
        ->bulkActions([...])

        // Pagination
        ->paginated([10, 25, 50, 100])
        ->defaultPaginationPageOption(25)

        // Default sort
        ->defaultSort('created_at', 'desc')

        // Reordering
        ->reorderable('sort_order')
        ->defaultSort('sort_order')

        // Grouping
        ->groups([
            Tables\Grouping\Group::make('status')
                ->label('Status')
                ->collapsible(),
            Tables\Grouping\Group::make('author.name')
                ->label('Author'),
        ])

        // Striped rows
        ->striped()

        // Poll for updates
        ->poll('10s')

        // Empty state
        ->emptyStateHeading('No posts yet')
        ->emptyStateDescription('Create your first post to get started.')
        ->emptyStateIcon('heroicon-o-document-text')
        ->emptyStateActions([
            Tables\Actions\CreateAction::make()
                ->label('Create Post'),
        ])

        // Modals
        ->modals([
            'view' => true,
        ])

        // Persist filters
        ->filtersFormColumns(3)
        ->persistFiltersInSession();
}

输出

生成的表格包括:

  1. 完整的列配置
  2. 搜索和排序设置
  3. 筛选器定义
  4. 行操作和批量操作
  5. 关联处理
  6. 性能优化

评论

支持 Markdown