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:
i tried things like these, but idk how to make it work, the field's value always remains
false
:
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
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')
.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 nowYou 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.having a field used only for presentational purposes is kinda tricky
i guess ill move that field to the db too then