F
Filament15mo ago
ILPAV

Best way to format money or date with default string value

Hello, I am wondering if exists an easy way to both use default() and money() or format() for dates when the default value is a string. If the value is null and so it is replaced with a string I get Filament\Support\format_money(): Argument #1 ($money) must be of type int|float, string given. The solution that I have found it uses formatStateUsing, for example:
use function Filament\Support\format_money;

// ...

Components\TextEntry::make('initial_cost')
->money('eur')
->label(__('Initial Cost')),

Components\TextEntry::make('final_cost')
->default(__('N/A'))
->formatStateUsing(fn (int|float|string $state): string => $state == __('N/A')
? $state
: format_money($state, 'eur'))
// : $state->money('eur')) this also gives the same error
->label(__('Final Cost')),
use function Filament\Support\format_money;

// ...

Components\TextEntry::make('initial_cost')
->money('eur')
->label(__('Initial Cost')),

Components\TextEntry::make('final_cost')
->default(__('N/A'))
->formatStateUsing(fn (int|float|string $state): string => $state == __('N/A')
? $state
: format_money($state, 'eur'))
// : $state->money('eur')) this also gives the same error
->label(__('Final Cost')),
Is there a better way to achieve this with using money() directly without formatStateUsing?
1 Reply
ILPAV
ILPAVOP15mo ago
The same is true when using format(), the best work around I got is this:
Components\TextEntry::make('invoice_date')
->default(__('N/A'))
->formatStateUsing(fn (string | Carbon $state): string => $state == __('N/A')
? $state
: $state->format('d/m/Y'))
->label(__('Invoice Date')),
Components\TextEntry::make('invoice_date')
->default(__('N/A'))
->formatStateUsing(fn (string | Carbon $state): string => $state == __('N/A')
? $state
: $state->format('d/m/Y'))
->label(__('Invoice Date')),
Components\TextEntry::make('final_cost')
->placeholder(__('N/A'))
->money('eur')
->label(__('Final Cost')),
Components\TextEntry::make('final_cost')
->placeholder(__('N/A'))
->money('eur')
->label(__('Final Cost')),
I guess using placeholder() instead of default() is also an option but the text displaying 'N/A' is obviously lighter
Want results from more Discord servers?
Add your server