Modifiy an option in a select

Hello, Is it possible to change one of the options in select to show the user the active number.
12 Replies
Pasteko
PastekoOP2y ago
I have probably to use ->getOptionLabelUsing but how can I replace one value in the query?
Patrick Boivin
Hi @pasteko, something like this could work :
Select::make('visibility')
->options(function ($get) {
$activeOption = $get('visibility');

return [
'draft' => 'Draft' . ($activeOption === 'draft' ? ' (active)' : ''),
'public' => 'Public' . ($activeOption === 'public' ? ' (active)' : ''),
'private' => 'Private' . ($activeOption === 'private' ? ' (active)' : ''),
];
})
// ...
Select::make('visibility')
->options(function ($get) {
$activeOption = $get('visibility');

return [
'draft' => 'Draft' . ($activeOption === 'draft' ? ' (active)' : ''),
'public' => 'Public' . ($activeOption === 'public' ? ' (active)' : ''),
'private' => 'Private' . ($activeOption === 'private' ? ' (active)' : ''),
];
})
// ...
awcodes
awcodes2y ago
according to the docs this should work:
->getOptionLabelUsing(fn ($value): ?string => $value . ' (active)',
->getOptionLabelUsing(fn ($value): ?string => $value . ' (active)',
Pasteko
PastekoOP2y ago
Thank you, I'll try that if I can't get it working with ->getOptionLabelUsing Sorry I don't understand where's the condition here?
Patrick Boivin
Not 100% sure but it seems like getOptionLabelUsing() would run for the currently selected item (before save), whereas the snippet above would add the (active) suffix after save.
Dan Harrin
Dan Harrin2y ago
that will only be run if the label isnt already present in the preloaded options
awcodes
awcodes2y ago
ah, nevermind then.
Pasteko
PastekoOP2y ago
So the solution is to build my options manually with conditions? Maybe my explanation was wrong, I don't need the selected or default value, the active state comes from a value in the numbers table.
Pasteko
PastekoOP2y ago
Pasteko
PastekoOP2y ago
I'm trying to populate the select with a relation and show the user the actual (active) number.
Patrick Boivin
If the options are coming from the DB and the active status is a column in the table, something like this might work :
->options(
Numbers::all()
->mapWithKeys(fn($item) => [$item->id => $item->number . ($item->active ? ' (active)' : '')])
)
->options(
Numbers::all()
->mapWithKeys(fn($item) => [$item->id => $item->number . ($item->active ? ' (active)' : '')])
)
Pasteko
PastekoOP2y ago
Thank you, it's working perfectly!
Want results from more Discord servers?
Add your server