DEV Community

JohnDivam
JohnDivam

Posted on

Filament Repeater, total sum & validate

  • Sum the values of all repeater rows
  • Validate the total against a maximum
  • Update another field automatically
return $form->schema([

    // This field will display the calculated total
    Forms\Components\TextInput::make('qnt_allocated')
       ->label('Total Quantity')
        ->required()
        ->numeric()
        ->suffix('Kg'),

    // Repeater of groups
    Forms\Components\Repeater::make('groups')
        ->label('groups:')
        ->relationship('groups')
        ->schema([
            Forms\Components\TextInput::make('quantity')
                ->label('group quantity')
                ->required()
                ->numeric()
                ->reactive()
                ->rules([
                    fn (Get $get): \Closure => function (string $attribute, $value, \Closure $fail) use ($get) {
                        $total = collect($get('../../groups'))->sum('quantity');
                        if ($total > 7000) {
                           $fail("Total quantity for all groups cannot exceed 7000 kg (Current total: {$total})");
                        }
                    },
                ])
                ->afterStateUpdated(function ($state, callable $get, callable $set) {
                    $total = collect($get('../../groups'))->sum('quantity');
                    $set('../../qnt_allocated', $total);
                })
                ->suffix('Kg'),
        ])
]);

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
prime_1 profile image
Roshan Sharma

Nice post! The Filament repeater sum validation is slick, a great solution for form validations.

Have you tried making it work with nested repeaters (repeaters inside repeaters) and how did validation behave?