F
Filamentβ€’11mo ago
pelmer

Turn formatStateUsing into a custom entry

I need the same formatStateUsing on many places across my admin panel so I was thinking that I should create a custom Entry / Input instead. I don't get how I should trigger the formatter in my custom entry. How would a simple entry look like with a custom formatter? Or are there any better solutions for this?
Solution:
then just create one. ```php CustomEntry extends TextEntry...
Jump to solution
6 Replies
awcodes
awcodesβ€’11mo ago
Just create a helper method somewhere in your app, like a Helpers class, then you can call it where ever you need it in ->formatStateUsing(fn ($state) => Helpers::customFormat($state))
pelmer
pelmerOPβ€’11mo ago
Thank you. Yes, that would work. But it would be cleaner and more clear what it is with new field type.
Solution
awcodes
awcodesβ€’11mo ago
then just create one.
CustomEntry extends TextEntry
{
protected function setUp(): void
{
parent::setUp();

$this->formatStateUsing(fn() => do stuff);
}
}
CustomEntry extends TextEntry
{
protected function setUp(): void
{
parent::setUp();

$this->formatStateUsing(fn() => do stuff);
}
}
pelmer
pelmerOPβ€’11mo ago
I tried exactly like that, but the formatStateUsing callback is never called. I only got it to work if I added a custom method that sets the formatStateUsing property
awcodes
awcodesβ€’11mo ago
you have to pass the component and state into it. for example:
$this->afterStateHydrated(static function (CustomEntry $component, string|null $state): void {
if (blank($state)) {
return;
}

$formattedState = do something to state;

$component->state($formattedState);
});
$this->afterStateHydrated(static function (CustomEntry $component, string|null $state): void {
if (blank($state)) {
return;
}

$formattedState = do something to state;

$component->state($formattedState);
});
pelmer
pelmerOPβ€’11mo ago
I figured it out now. Thanks a lot! πŸ˜€ That was helpful πŸ™
Want results from more Discord servers?
Add your server