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

Filament框架中动态修改批量操作按钮标签问题求助

解决Filament中动态修改DeleteBulkAction按钮标签的问题

要实现选中1条记录时显示“Trash can”,选中多条时显示“Remove from creators”,只需将label方法的静态值替换为接收选中记录集合的闭包,根据集合数量返回对应文本即可。

修改后的代码

class CreatorResource extends Resource
{
    protected static ?string $model = User::class;

    protected static ?string $navigationIcon = 'heroicon-o-paint-brush';

    protected static ?string $navigationLabel = 'Creators';

    protected static ?string $label = 'Creators';

    protected static ?string $slug = 'authors';

    public static function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(static function ($query) {
                $query->leftJoin('model_has_roles', 'model_has_roles.model_id', '=', 'users.id')
                    ->where('model_has_roles.role_id', '=', UserRole::CREATOR->value);
            })
            ->columns([
                TextColumn::make('name')
                    ->searchable()
                    ->sortable(),
            ])
            ->actions([
                Action::make('trash')
                    ->label('')
                    ->icon('heroicon-o-trash')
                    ->action(static function (User $user) {
                        return $user->removeRole(UserRole::CREATOR->value);
                    }),
            ])
            ->bulkActions([
                DeleteBulkAction::make()
                    ->successNotificationTitle(__('Removed'))
                    // 核心修改:用闭包动态生成标签
                    ->label(function (Collection $records) {
                        return count($records) === 1 ? __('Trash can') : __('Remove from creators');
                    })
                    ->modalHeading(__('Remove users'))
                    ->modalSubmitActionLabel(__('Yes, remove it'))
                    ->action(static function (Collection $records) {
                        $records->each(static function ($user) {
                            assert($user instanceof User);
                            $user->removeRole(UserRole::CREATOR->value);
                        });
                    }),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListCreators::route('/'),
        ];
    }
}

关键说明

  • Filament的批量操作组件支持通过闭包动态设置label,闭包会接收当前选中的记录集合$records作为参数。
  • 直接通过count($records)判断选中数量,返回对应的翻译文本即可实现需求。

内容的提问来源于stack exchange,提问作者Anton Zimyanin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 06:27:41