How to make a custom titleAttribute in Select::make('course_id')->relationship ?
Hello
I want to change titleAttribute. I need to display additional fields in the option names.
Select::make('course_id')
->relationship('course', 'number')
->searchable()
I want for example: ->relationship('course', 'number title year')
How to do it?
And the search also needs to work by full name.13 Replies
use
options
instead and a callback and specify your table columns. Then in your ->searchable([columns])
I have millions of records. If I use options will it work well?
if you have millions of records, use this
getOptionLabelUsing
and getSearchResultsUsing
https://filamentphp.com/docs/3.x/forms/fields/select#returning-custom-search-resultsHow to use getTitle() in getSearchResultsUsing?
getTitle() is my custom function in the Course model.
->getSearchResultsUsing(fn(string $search, Select $component): array => Course::whereAny($component->getSearchColumns(), 'like', "%{$search}%")->limit(50)->pluck('title', 'id')->toArray())
->getOptionLabelUsing(fn($value): ?string => Course::find($value)->getTitle())
You can customize it and return an array format with your custom format data
Can you make a working example?
This is a manual array.
Look at my code:
->getSearchResultsUsing(fn(string $search, Select $component): array => Course::whereAny($component->getSearchColumns(), 'like', "%{$search}%")->limit(50) ->pluck('title', 'id')->toArray())
->pluck('title', 'id')
title as the option name. I want to make a combined title like 'title year'
The best way is to use my getTitle() function
How to do it?OK. I think this can be done somehow easier. Thank you.
you can play around with this
instead of foreach i think mapWithKeys could be used if you prefer collections
Correct solution to the problem:
Select::make('course_id')
->relationship('course', 'title')
->getOptionLabelFromRecordUsing(fn(Course $record) => $record->getTitle())
->searchable(['title', 'number', 'year'])