Handling a Primary Item Outside the Repeater

I’m using Filament with a 1:N relationship represented by a repeater. Among these items, one must be marked as the “primary” item, which is stored in a specific column. Because of this, I’ve separated the primary item field from the repeater in the form. I renamed it in the make method, and before saving the other items in the repeater, I add this primary item first. However, Filament is interpreting the separated primary item field as another relationship, but I want it to be ignored by the relationship handling. I’ve tried using dehydrated, but it didn’t work. How can I ensure that Filament doesn’t treat this primary item field as part of a new relationship, and instead just handles it as a regular field to be saved before persisting the repeater’s items? This is a generic example:
Grid::make()
->columns(4)
->schema([
Select::make('main_attachment_id')
->label('Main Attachment')
->options(Attachment::pluck('name', 'id'))
->dehydrated()
->required()
->columnSpan(2),
]),

TableRepeater::make('attachments')
->relationship('attachments')
->schema([
TextInput::make('name')->required(),
Hidden::make('is_main')->default(false),
])
->beforeStateDehydrated(function ($component, $get) {
$state = $component->getState();
$state[] = [
'id' => $get('main_attachment_id'),
'name' => Attachment::find($get('main_attachment_id'))?->name,
'is_main' => true,
];
$component->state($state);
})
->afterStateHydrated(function ($component, $set) {
$state = $component->getState();
$filtered = [];

foreach ($state as $item) {
if (! empty($item['is_main'])) {
$set('main_attachment_id', $item['id']);
} else {
$filtered[] = $item;
}
}

$component->state($filtered);
});
Grid::make()
->columns(4)
->schema([
Select::make('main_attachment_id')
->label('Main Attachment')
->options(Attachment::pluck('name', 'id'))
->dehydrated()
->required()
->columnSpan(2),
]),

TableRepeater::make('attachments')
->relationship('attachments')
->schema([
TextInput::make('name')->required(),
Hidden::make('is_main')->default(false),
])
->beforeStateDehydrated(function ($component, $get) {
$state = $component->getState();
$state[] = [
'id' => $get('main_attachment_id'),
'name' => Attachment::find($get('main_attachment_id'))?->name,
'is_main' => true,
];
$component->state($state);
})
->afterStateHydrated(function ($component, $set) {
$state = $component->getState();
$filtered = [];

foreach ($state as $item) {
if (! empty($item['is_main'])) {
$set('main_attachment_id', $item['id']);
} else {
$filtered[] = $item;
}
}

$component->state($filtered);
});
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server