F
Filament2mo ago
john

Setting default value for Checkbox (forms) is not working

I am trying to set a default value for a Checkbox. Basically I am trying to get a value from the database and then based on a specific condition, check/uncheck the box automatically. Here is the code snippet:
Checkbox::make('subscription_never_ends')
->label('Subscription never ends')
->reactive()
->default(function (OfflinePayment $record) {
$stripeId = 'offline_' . $record->transaction_id;
$subscription = DB::table('subscriptions')
->where('stripe_id', $stripeId)
->first();

Log::info($subscription);

return $subscription && $subscription->ends_at === null;
})
Checkbox::make('subscription_never_ends')
->label('Subscription never ends')
->reactive()
->default(function (OfflinePayment $record) {
$stripeId = 'offline_' . $record->transaction_id;
$subscription = DB::table('subscriptions')
->where('stripe_id', $stripeId)
->first();

Log::info($subscription);

return $subscription && $subscription->ends_at === null;
})
5 Replies
LeandroFerreira
LeandroFerreira2mo ago
Are you using form builder in a custom livewire component? Did you add $this->form->fill() in the mount method?
Jorge Romera
Jorge Romera2mo ago
Note that these defaults are only used when the form is loaded without existing data
john
johnOP2mo ago
No. I was doing it inside the
public static function form(Form $form): Form
public static function form(Form $form): Form
inside the resource So, what to do if I want to set the value based on some saved user value? For example, if $record->value > 5, check the checkbox, else uncheck
LeandroFerreira
LeandroFerreira2mo ago
default() only works in the CreatePage. If you want to use it in the EditPage, I think you can use formatStateUsing() instead

Did you find this page helpful?