F
Filament17mo ago
Veur

Determine Toggle label by state

Is there a way to change the label of a \Filament\Forms\Components\Toggle based on its value? This is what I tried, but it doesn't work: Toggle::make('active') ->label(fn ($record) => $record->active ? 'Active' : 'Inactive')
12 Replies
Dennis Koch
Dennis Koch17mo ago
What's not working? You tried with two records with different state?
Veur
Veur17mo ago
Sorry, I mean I want the label to change when the user toggles the Toggle input
Veur
Veur17mo ago
Something like this:
Dennis Koch
Dennis Koch17mo ago
Make it reactive and use fn ($get) and not the record. Check the docs for Closure Customization for more infos You can probably use fn ($state) as well
awcodes
awcodes17mo ago
since it's referencing itself, I'd go with $state as Dennis recommends
Veur
Veur17mo ago
Thanks! Now it works: Toggle::make('active') ->label(fn ($state) => $state ? 'Active' : 'Inactive') ->reactive(),
Ander
Ander15mo ago
hello, how can i achieve this but with a filter
awcodes
awcodes15mo ago
dd() the state to see what it actually is. It could be on/off 1/0 or true/false. It depends on how you model is structured.
Ander
Ander15mo ago
thanks, i solved it in another way
Ander
Ander15mo ago
Ander
Ander14mo ago
I leave this here, in case it helps someone, this was what was translated to do a while ago with the table filter:
->filters([
Filter::make('status_employees')
->form([
Toggle::make('employees')
->default(false)
->label(fn($state) => $state ? 'Inactivos' : 'Activos')
->reactive()
])
->query(fn (Builder $query, array $data): Builder => $query->where('active', !$data['employees']))
])
->filters([
Filter::make('status_employees')
->form([
Toggle::make('employees')
->default(false)
->label(fn($state) => $state ? 'Inactivos' : 'Activos')
->reactive()
])
->query(fn (Builder $query, array $data): Builder => $query->where('active', !$data['employees']))
])
Bestun
Bestun8mo ago
I was searching for how to change helperText() return string based on the states of the toggle. It accepts a closure; so the way worked for me was: toggle::make(is_visible)->label('Visibility)->helperText(fn ($state): string => $state? 'Visible' : 'Hidden')->reactive(), You should not forget to use the $state and the reactive() method in order to be changing after state update.