F
Filamentā€¢2mo ago
Benjamin

validate() vs getState()

Hi guys ! I'm using a custom Form inside a Livewire component and I need to understand the difference between validate() and getState(). Here is my code :
public function create(): void
{
$data = $this->form->validate(); // I get validated data, without hidden fields such as `has_blabla`
$dataBis = $this->form->getState(); // I get validated data, with hidden fields such as `has_blabla`, is it normal ?
}
public function create(): void
{
$data = $this->form->validate(); // I get validated data, without hidden fields such as `has_blabla`
$dataBis = $this->form->getState(); // I get validated data, with hidden fields such as `has_blabla`, is it normal ?
}
I'm reusing form fields across multiple forms and some fields needs to be hidden (for the user + in the data), like this one :
Components\TextInput::make('has_blabla')
->label('blabla')
->required()
->visible(fn (): bool => $this->formType === FormTypeEnum::WITNESS),
Components\TextInput::make('has_blabla')
->label('blabla')
->required()
->visible(fn (): bool => $this->formType === FormTypeEnum::WITNESS),
5 Replies
awcodes
awcodesā€¢2mo ago
validate only returns fields that are marked to be validated. GetState runs the validation and returns all fields.
Benjamin
BenjaminOPā€¢2mo ago
Okay thanks! But I see that getSate() is doing some other stuff (dehydrateState, mutateDehydratedState(), etc.), so it that safe to just call $this->form->validate() ? Maybe I need to run them both ?
awcodes
awcodesā€¢2mo ago
getState() is the proper way to get all the processed form data. If you need to do anything with the data before then, that is what those other methods are for.
Benjamin
BenjaminOPā€¢2mo ago
Okay, so if I don't want to save some data in my database, I should call getState() and manually remove them from the array, even if the components are ->hidden() ? šŸ§ My hope was to just use ->hidden() on some components conditionally to not save them later.
awcodes
awcodesā€¢2mo ago
If they are hidden they shouldnā€™t be in the form data, by default. If they are for some reason, thereā€™s also the ->dehydrate() method you could use, or remove them in one of the other lifecycle hooks. You could manually remove them after get state though. None of this is right or wrong, just options. Every app has different needs.
Want results from more Discord servers?
Add your server