ariaieboy / filament-currency

Enhanced Currency Related stuff for Filament
MIT License
49 stars 8 forks source link

[Bug]: #3

Closed 0chak closed 1 year ago

0chak commented 1 year ago

What happened?

Hi,

I need to show my currency in euro-style format ( 1.000,00 ): If I type some number, it gets formatted right, validated right and saved right, but if just I load the edit page, don't touch the field and hit save, it gives me the error "Field x must be a number"

How to reproduce the bug

Forms\Components\TextInput::make('security_deposit')
        ->minValue(0)
        ->numeric()
        ->formatStateUsing(fn (?string $state): string => $state ? number_format($state, 2, ',', '.') : '')
        ->currencyMask(thousandSeparator: '.',decimalSeparator: ',',precision: 2)
        ->default(0)
        ->prefix('€')

security_deposit is a decimal(10,2) column in the db

no casts are used

enter some value, save it, reload the page, the field should be populated (till here ok), don't edit the field, hit save again, wrong validation appears

Package Version

1.1.0

PHP Version

8.2.2

Laravel Version

10.24.0

Which operating systems does with happen with?

No response

Notes

No response

ariaieboy commented 1 year ago

Remove formatStateUsing method

0chak commented 1 year ago

Without formatStateUsing, the number gets displayed wrong: I have 1000.22 in the database but I see 100.022 in the field instead of 1.000,22

0chak commented 1 year ago

so far the only workaround I found is to use a Cast on the model:


namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;

class MoneyCast implements CastsAttributes
{
    public function get(Model $model, string $key, mixed $value, array $attributes): mixed
    {
        return floatval($value);
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): mixed
    {
        if (str_contains($value, ',') && str_contains($value, '.')) {
            return floatval(str_replace(',', '.', str_replace('.', '',$value)));
        }
        return floatval($value);
    }
}

in model:

 protected $casts = [
      'security_deposit' => MoneyCast::class,
  ];

and remove ->numeric() from the field but this way it allows me to input negative values because it ignores ->minValue(0) so I have to make also a custom validation rule basically its a mess

ariaieboy commented 1 year ago

Hi, @0chak Update the plugin to 1.1.1 then clear the view cache. remove the formatStateUsing method and test it again. the problem should be fixed.