Select filter grouping options in relation filter
I am struggling to get a Select filter on a relation working with option groups described here: https://filamentphp.com/docs/3.x/forms/fields/select#grouping-options
This is my Select field in the table filters:
The format of the options is right and they get displayed correctly with the groups, butwhen i select an entry, I get this error:
How can I configure the select so its checking the relation. When I use ->relation() it takes the options from the relation and not from the customized option array. Thanks.
7 Replies
electFilter::make('trends')
->label(__('Trends'))
->searchable()
->options($formattedData)
->preload(),
where is $formattedData?
options for should a closure:
->options(fn() => $formattedData)
If it is a relationshjip, then why are you not using
->relationship()
The data is in this form (as described in the doc at https://filamentphp.com/docs/3.x/forms/fields/select#grouping-options):
If I use ->relationship() it takes the options from the relation and not from the grouped options.
Was anyone able to get Option Groups to work with a relationship in a SelectFilter? It seems that using ->relationship() overwrites the provided ->options() so it is not displayed in groups.
@Sascha did you ever figure this out? I have the same issue.
So relationship does overwrite the options, if you place the options after the relationship does that work?
It didn't for me. I ended up using a custom filter instead:
This is my current code that works for me:
Filter::make('productCategories')
->form([
Select::make('productCategories')
->label(__('Product Categories'))
->multiple()
->preload()
->optionsLimit(150)
->options(
$groupedProductCategories
),
])
->query(function (Builder $query, array $data): Builder {
return $query
->when(
$data['productCategories'],
fn (Builder $query, $productCategories): Builder => $query->whereHas(
'productCategories',
function ($q) use ($productCategories) {
$q->whereIn('product_categories.id', $productCategories);
}
)
);
})