F
Filament8mo ago
ericmp

How to set default state of a field conditionally on Edit page

In my filament resource, when i try to edit a specific model, all fields r filled automatically, okay. but id like to also fill a field which is used only for presentational purposes. how can i do it? this is the field id like to fill:
Forms\Components\Toggle::make('has_users')
->live()
->dehydrated(false)
Forms\Components\Toggle::make('has_users')
->live()
->dehydrated(false)
i tried things like these, but idk how to make it work, the field's value always remains false:
->default(function (string $operation, Payment $record): bool {
if ($operation === 'create') {
return true;
}

return $record->users()->count() > 0;
})
->default(function (string $operation, Payment $record): bool {
if ($operation === 'create') {
return true;
}

return $record->users()->count() > 0;
})
default only works on Create Pages - https://filamentphp.com/docs/3.x/forms/fields/getting-started#setting-a-default-value so how to make it work in Edit Pages? any alternatives?
4 Replies
MohamedSabil83
MohamedSabil838mo ago
There's many options to do that using: - Make an attribute in your model to return that value. - Use ->formatStateUsing() method. - Override the getEloquentQuery() method to chain ->withCount('users). In this case, you'll use it in the form like ('users_count').
ericmp
ericmp8mo ago
i did the 2nd one, thanks! it works but lets say when i want to submit the form, if has_users is false, i want to remove the relationships that the model has with users. how that can be achieved? with normal fields would be afterStateUpdated - https://filamentphp.com/docs/3.x/forms/advanced#field-updates but for relationships, would also do the trick, i dont think - but im gonna test it now
MohamedSabil83
MohamedSabil838mo ago
You can't use ->afterStateUpdated() here, because if remove the relation when toggling it will applied even you didn't submit the form. If has_users was a real field in your DB, you can use life-cycle hook method afterSave() in the EditModel page. In that method, you can check $this->record->has_users and act according to the value.
ericmp
ericmp8mo ago
having a field used only for presentational purposes is kinda tricky i guess ill move that field to the db too then
Want results from more Discord servers?
Add your server