You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Filament批量操作:仅对选中行求和并获取选中行详情

Filament表格开发解决方案

需求1:获取批量操作的选中行详情

批量操作内直接获取选中记录

你当前批量操作的action闭包中,$records参数就是选中行的Eloquent集合,可直接遍历获取每条记录的详情:

->action(function ($records) {
    // 遍历选中记录,提取所需字段
    foreach ($records as $record) {
        $orderId = $record->id;
        $driverName = $record->driver->name;
        // 按业务需求处理单条记录数据
    }
    $this->generateCollectionList($records, $this->tableFilters['driver_id']['value']);
})

实时监听选中事件(非批量操作触发时)

如果需要在用户选中行时实时同步获取详情,可在组件类中添加Livewire监听逻辑:

  1. 定义存储选中记录的属性:
public $selectedRecords = [];
  1. 监听Filament表格选中事件:
protected $listeners = [
    'tableRecordsSelected' => 'handleSelectedRecords',
];

public function handleSelectedRecords($selectedRecordIds)
{
    // 根据ID查询完整的选中记录
    $this->selectedRecords = Order::whereIn('id', $selectedRecordIds)->get();
    // 此处可触发后续逻辑,比如更新求和统计
}

需求2:Sum::make()仅计算选中行总和

默认的Sum::make()是数据库层面的全局聚合,要实现仅对选中行求和,需替换为前端实时计算:

步骤1:移除列中的全局聚合

删掉原列的summarize(Sum::make()),保留基础列配置:

TextColumn::make('total_price')->money('IQD')->searchable(),
TextColumn::make('captured_amount')->money('IQD')->searchable(),
TextColumn::make('wallets_amount')->money('IQD')->searchable(),

步骤2:添加自定义求和表尾

在表格配置中添加自定义表尾,用于渲染选中行的求和结果:

->footer(fn (Table $table) => view('filament.tables.order-summary', [
    'selectedRecords' => $this->selectedRecords,
]))

步骤3:创建求和视图文件

在resources/views/filament/tables/order-summary.blade.php中写入:

<div class="flex justify-end gap-4 p-4 bg-gray-50">
    <div>
        <p class="text-sm text-gray-500">选中行总价:</p>
        <p class="font-semibold">{{ number_format($selectedRecords->sum('total_price'), 2) }} IQD</p>
    </div>
    <div>
        <p class="text-sm text-gray-500">选中行实收金额:</p>
        <p class="font-semibold">{{ number_format($selectedRecords->sum('captured_amount'), 2) }} IQD</p>
    </div>
    <div>
        <p class="text-sm text-gray-500">选中行钱包金额:</p>
        <p class="font-semibold">{{ number_format($selectedRecords->sum('wallets_amount'), 2) }} IQD</p>
    </div>
</div>

步骤4:关联选中事件更新统计

结合需求1的实时监听逻辑,当用户选中/取消选中行时,$selectedRecords会自动更新,视图也会实时刷新求和结果。

完整修改后的table方法示例

public function table(Table $table): Table
{
    return $table
        ->query(Order::query()->whereNotNull(['captured_at'])->latest())
        ->columns([
            TextColumn::make('id')->searchable(),
            TextColumn::make('identifier')->searchable(),
            TextColumn::make('driver.name')->searchable(),
            TextColumn::make('total_price')->money('IQD')->searchable(),
            TextColumn::make('captured_amount')->money('IQD')->searchable(),
            TextColumn::make('wallets_amount')->money('IQD')->searchable(),
            TextColumn::make('captured_status')->badge()->searchable(),
            TextColumn::make('captured_at')->date()->searchable(),
        ])
        ->bulkActions([
            BulkAction::make('Create')
                ->label(fn () => $this->tableFilters['driver_id']['value'] == null ? __('Select a driver') : __('Collect'))
                ->icon(fn () => $this->tableFilters['driver_id']['value'] == null ? '' : 'heroicon-o-plus')
                ->color(fn () => $this->tableFilters['driver_id']['value'] == null ? 'danger' : 'primary')
                ->action(fn ($records) => $this->generateCollectionList($records, $this->tableFilters['driver_id']['value']))
                ->requiresConfirmation()
                ->disabled(fn () => $this->tableFilters['driver_id']['value'] == null)
                ->modalHeading('Create Collection List ?')
                ->modalDescription(fn($records) => new HtmlString("You're going to create a collection list for <strong style='color:lime'>{$records->count()}</strong> orders of <strong style='color:lime'> {$this->getDriverName($records)} </strong> ?"))
                ->modalSubmitActionLabel('Yes, create it')
                ->deselectRecordsAfterCompletion()
        ])
        ->footer(fn (Table $table) => view('filament.tables.order-summary', [
            'selectedRecords' => $this->selectedRecords,
        ]))
        ->striped()
        ->defaultSort('created_at', 'desc');
}

// 组件类新增属性与监听
public $selectedRecords = [];

protected $listeners = [
    'tableRecordsSelected' => 'handleSelectedRecords',
];

public function handleSelectedRecords($selectedRecordIds)
{
    $this->selectedRecords = Order::whereIn('id', $selectedRecordIds)->get();
}

内容的提问来源于stack exchange,提问作者hayder hatem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:25:47