行分组
概述
使用共同的属性,你可以允许用户将表格行分组到一起。这对于以更有组织的方式显示大量数据非常有用。
可以使用要分组的属性名称(例如 status)或允许你自定义该分组行为的 Group 对象(例如 Group::make('status')->collapsable())来设置分组。
默认行分组
你可能希望始终使用指定属性对文章进行分组。要执行此操作,请将该分组传递给 defaultGroup() 方法:
use Filament\Tables\Table;
public function table(Table $table): Table
{
return $table
->defaultGroup('status');
}

允许用户选择分组
将分组名以数组的方式传入到 groups() 方法,你可以允许用户在不同分组之间进行选择:
use Filament\Tables\Table;
public function table(Table $table): Table
{
return $table
->groups([
'status',
'category',
]);
}
你可以同时使用 groups() 和 defaultGroup(), 让用户在不同分组中选择的同时,有一个默认分组设置:
use Filament\Tables\Table;
public function table(Table $table): Table
{
return $table
->groups([
'status',
'category',
])
->defaultGroup('status');
}
通过关联属性分组
使用点语法,你也可以通过关联属性进行分组。比如,author 关联中有一个 name 属性,你可以使用 author.name 作为属性名称:
use Filament\Tables\Table;
public function table(Table $table): Table
{
return $table
->groups([
'author.name',
]);
}
设置分组标签
默认情况下,分组标签会基于属性名生成。你可以在 Group 对象中使用 label() 方法,对其进行自定义:
use Filament\Tables\Grouping\Group;
use Filament\Tables\Table;
public function table(Table $table): Table
{
return $table
->groups([
Group::make('author.name')
->label('Author name'),
]);
}
设置分组标题
默认情况下,分组的标题是属性值。你可以在 Group 对象的 getTitleFromRecordUsing() 方法中返回一个新标题,来对其进行自定义:
use Filament\Tables\Grouping\Group;
use Filament\Tables\Table;
public function table(Table $table): Table
{
return $table
->groups([
Group::make('status')
->getTitleFromRecordUsing(fn (Post $record): string => ucfirst($record->status->getLabel())),
]);
}
禁用标题标签前缀
默认情况下,标题使用分组标签作为前缀。要禁用该前缀,请使用 titlePrefixedWithLabel(false) 方法:
use Filament\Tables\Grouping\Group;
use Filament\Tables\Table;
public function table(Table $table): Table
{
return $table
->groups([
Group::make('status')
->titlePrefixedWithLabel(false),
]);
}
设置分组描述
你也可以为分组设置描述,它会展示在分组标题下面。为此,请在 Group 对象中使用 getDescriptionFromRecordUsing() 方法:
use Filament\Tables\Grouping\Group;
use Filament\Tables\Table;
public function table(Table $table): Table
{
return $table
->groups([
Group::make('status')
->getDescriptionFromRecordUsing(fn (Post $record): string => $record->status->getDescription()),
]);
}
设置分组键
默认情况下,分组的键是该属性的值。它在内部用作该分组的行标识符,而不是标题。使用 Group 对象的 getKeyFromRecordUsing() 方法,使之返回新的键,你可以对其进行自定义:
use Filament\Tables\Grouping\Group;
use Filament\Tables\Table;
public function table(Table $table): Table
{
return $table
->groups([
Group::make('status')
->getKeyFromRecordUsing(fn (Post $record): string => $record->status->value),
]);
}
