Trim each input

Hi all. Please tell me how best to implement the functionality for removing spaces at the beginning and end of a line for each input? It seems labor-intensive to me to write hooks everywhere. Middleware TrimStrings does not work.
5 Replies
toeknee
toeknee9mo ago
mutateDataBeforeSave? Then loop the $data array with a trim?
Epko
Epko2mo ago
This is indeed working, and probably the best solution. I find it strange this is not the default behaviour in Filament, as it is the default behaviour in Laravel (https://laravel.com/docs/11.x/validation#a-note-on-optional-fields). For anyone having the same issue, this is how I implemented it (thanks to the suggestion of @toeknee):
protected function mutateFormDataBeforeSave(array $data): array
{
foreach ($data as $key => $value) {
$data[$key] = is_string($value) ? trim($value) : $value;
}
return $data;
}
protected function mutateFormDataBeforeSave(array $data): array
{
foreach ($data as $key => $value) {
$data[$key] = is_string($value) ? trim($value) : $value;
}
return $data;
}
But I have to repeat this in every Edit page.
Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
awcodes
awcodes2mo ago
Just configure the Field class globally. And use ->dehydrateStateUsing() to do the trimming. Then any field that extends Field will be trimmed. https://filamentphp.com/docs/3.x/infolists/layout/getting-started#global-settings
Epko
Epko2mo ago
Added this to AppServiceProvider:
use Filament\Forms;
public function boot(): void
{
Forms\Components\TextInput::configureUsing(function (Forms\Components\TextInput $textInput): void {
$textInput
->dehydrateStateUsing(function (?string $state): ?string {
return is_string($state) ? trim($state) : $state;
});
});
}
use Filament\Forms;
public function boot(): void
{
Forms\Components\TextInput::configureUsing(function (Forms\Components\TextInput $textInput): void {
$textInput
->dehydrateStateUsing(function (?string $state): ?string {
return is_string($state) ? trim($state) : $state;
});
});
}
Works perfectly. Thanks for the hint @awcodes !
Vazaios
Vazaios2mo ago
No description