zacktagnan
zacktagnan

Reputation: 141

Unique validation inside a Filament Repeater

I have a Laravel project with Filament for the admin panel. I have two models: Course and Unit. A Course can HaveMany Unit. A Unit BelongsTo a Course.

Inside the CourseResource form, I implement a Wizard component to have Multistep form. The first two steps to set/edit the course's data, the third step, with a Repeater component, is to manage the course's unit(s).

What I want to achieve is an Unique rule to ensure create/edit Unit with unique name but only between those who belong to the same course.

I only know the basic Unique rule to ensure the unique name value between all the registered units like this:

    TextInput::make('name')
        ->unique(Unit::class, 'name', ignoreRecord: true)

And I have only achieved this which is only works for the edit context:

    use Illuminate\Validation\Rules\Unique;

    TextInput::make('name')
        ->unique(Unit::class, 'name', ignoreRecord: true, modifyRuleUsing: function (Unique $rule, string $context, ?Model $record) {
            return $rule
                ->where('course_id', $record->course_id)
        })

So how I have to implement the Unique rule to validate Unique Unit name between the units who belong to the same course only. Both in the create context and the edit context.

Regards.

Upvotes: 2

Views: 2225

Answers (2)

Justice Ekemezie
Justice Ekemezie

Reputation: 21

Simply use the ->distint() method:

 Checkbox::make('is_correct')->distinct(),

// Or

  Forms\Components\TextInput::make('account_name')
     ->label('Account Name')
     ->required()
     ->distinct()
     ->helperText('Account name must be unique.'),

Filament distinct State validation

Upvotes: 1

Bilal Amin
Bilal Amin

Reputation: 1

You can use the disableOptionWhen() method like so:

Forms\Components\Select::make('attribute_id')
                            ->options(Attribute::all()->pluck('attribute_name', 'id'))
                            ->label('Name')
                            ->searchable()
                            ->disableOptionWhen(function ($value, $state, Get $get) {
                                return collect($get('../*.attribute_id'))
                                    ->reject(fn($id) => $id == $state)
                                    ->filter()
                                    ->contains($value);
                            })
                            ->required(),

For more check out this link Filament Repeater form key value pair

Upvotes: 0

Related Questions