#How do i ignore saving of empty repeater relationship fields.

11 messages · Page 1 of 1 (latest)

tribal briar
#

I have a repeater filed for one of my models that add s alterative names to a hobby. since not all hobbies have alternative names, this field is often empty.

But if I do not manually delete the empty repeater field, I get an error that name is required.

But the underlining hobby saves but without the attached media or other related items. Then if I remove the empty alt names and attempt to save again, I get an error that slug already exists.

So how do i instruct filament to ignore related repeater fields if empty. If I create 5 rows, but only enter 1, It should only attempt to save 1 without error on the other 5.

Also, if the underlining model is saving, shouldnt the page refresh to an update form? or have some check to save as the existing model?

TextInput:: make('name')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(function (
Get $get,
Set $set,
?string $old,
?string $state
) {
if (($get('slug') ?? '') !== Str::slug($old)) {
return;
}

         $set('slug', Str::slug($state));
     }),

// TODO slug not generating properly without the name input disappearing when typing
TextInput::make('slug')
->maxLength(255)
->helperText('Generated slugs can be renamed if desired but must be unique'),
Repeater::make('Alternative Names')
->label('Alternative names')
->relationship('hobbyAltNames')
->simple(
TextInput::make('name'),
),
])->columnSpan(1),

abstract craneBOT
#

To help others find answers, you can mark your question as solved via Right click solution message -> Apps -> ✅ Mark Solution

primal ferry
#

I found a solution to solve your problem

stiff lintel
primal ferry
#
  1. Ignore Empty Rows in Repeater Field
#

2.Handle Slug Errors

#

3.Page Refresh or Update Form on Model save

#

try with the above tips

tribal briar
tribal briar
#

i finally found a solution that works:

Repeater::make('Alternative Names')
->label('Alternative names')
->relationship('hobbyAltNames')
->simple(
TextInput::make('name')

    )
    ->mutateRelationshipDataBeforeCreateUsing(function (array $data
    ): ?array {
        // Check if the name is empty
        if (empty($data['name'])) {
            return null; // Return null to prevent saving this item
        }

        return $data; // Return the modified data
    })

Im thinking it would be worth it for the filament team to include a "ignoreEmptyRows" function to make this process easier.