F
Filamentβ€’12mo ago
Masea

Default value for checkboxes and toggles

Hey I tried to make the toggle checked by default with this code but it doesn't work. Any idea why?
Solution:
Uh my bad it is because i am filling the form at somewhere else
Jump to solution
18 Replies
awcodes
awcodesβ€’12mo ago
note that default only works in the 'create' context
Masea
Maseaβ€’12mo ago
Sure. but it isn't checked even in the create page
awcodes
awcodesβ€’12mo ago
are you on v2 or v3?
Solution
Masea
Maseaβ€’12mo ago
Uh my bad it is because i am filling the form at somewhere else
Masea
Maseaβ€’12mo ago
deleting this now
awcodes
awcodesβ€’12mo ago
don't delete it
Masea
Maseaβ€’12mo ago
Got it
awcodes
awcodesβ€’12mo ago
it could help others,
awcodes
awcodesβ€’12mo ago
glad you found it though.
Masea
Maseaβ€’12mo ago
Thanks Since it is related though, i would like to talk about reactive checkboxes and toggles. So I have another field that is only visible when a toggle is checked. This is all fine when creating the record for the first time. Imagine I have created a record and actually enabled the toggle to also fill the field. (Note that i am not saving the enabled toggle field to the database). So next time when I am editting the record, the toggle field should be enabled by default since its related field was filled up. How can i achieve this?
awcodes
awcodesβ€’12mo ago
->afterStateHydrated() you can use that to set the state of other fields
awcodes
awcodesβ€’12mo ago
Filament
Advanced - Form Builder - Filament
The elegant TALL stack form builder for Laravel artisans.
Masea
Maseaβ€’12mo ago
I am on the v2. Thanks. Which field am i going to use this tho? The toggle field or the field that is only visible when the toggle is on
awcodes
awcodesβ€’12mo ago
since it depends on the related field being filled, I would use it on the related field
ReleatedField::make('blah')
->afterStateHydrated(function(Closure $set, $state) {
if ($state !== null) {
$set('toggle', true);
}
})
ReleatedField::make('blah')
->afterStateHydrated(function(Closure $set, $state) {
if ($state !== null) {
$set('toggle', true);
}
})
something like that obviously you'll need to handle the if check better than that. LOL.
Masea
Maseaβ€’12mo ago
Thank you! Like how? πŸ˜„ It felt completely reasonable to me tbh
awcodes
awcodesβ€’12mo ago
i don't know the data for the related field, it could have been a repeater with an array of data. πŸ™‚ could also use filled($state) or empty($state) depending on the type of data.
Masea
Maseaβ€’12mo ago
Ok thank you so much for the help