In this lesson, I will show you how to customize the behavior with the field value, both in the form and table, with an example of the Money field.
We have a products.price
DB field, which requires extra logic. According to all the DB theories, we shouldn't store monetary values as floats. Instead, we should use an integer field and store the value in cents.
It means that after someone enters 49.99
in the form, we need to automatically multiply it by 100 and save 4999
in the DB.
It also means that, from the other side, in the table, we need to take the 4999
value from the DB and automatically divide it by 100 to show 49.99
in the table column.
Let's see how to do both in Filament.
Filament has methods to modify the value between entering it in the form and saving it in the DB.
mutateFormDataBeforeCreate()
for Create formsmutateFormDataBeforeSave()
for Edit formsThey both accept the array of field values, and we can modify that array however we want and return it from the function.
app/Filament/Resources/ProductResource/Pages/CreateProduct.php:
class CreateProduct extends CreateRecord{ // ... protected function mutateFormDataBeforeCreate(array $data): array { $data['price'] = $data['price'] * 100; return $data; }}
Now, if we enter 123.45
in the create form field, it will show 12345
both in the database and in the table:
Let's fix that table column value.
We will add two modifier methods: dividing the value by 100 and formating the value with a currency.
For re-calculating the value from DB, you can use the ->getStateUsing()
method, which acts similarly to the Eloquent Accessor.
For formatting the monetary value with separators, we can just add a method ->money()
to the column. Not only that, we can specify which currency to show.
Tables\Columns\TextColumn::make('price') ->sortable() ->money('usd') ->getStateUsing(function (Product $record): float { return $record->price / 100; }),
Now, if I add a price of 12345.67
to a new product, it will look like this in the table:
Now, if we load the Edit form, we will have the same problem: the value will come exactly as it is in the DB: 1234567
instead of 12345.67
.
And also, when saving, there won't be any modification either. So let's fix both with two methods:
app/Filament/Resources/ProductResource/Pages/EditProduct.php:
class EditProduct extends EditRecord{ // ... protected function mutateFormDataBeforeFill(array $data): array { $data['price'] = $data['price'] / 100; return $data; } protected function mutateFormDataBeforeSave(array $data): array { $data['price'] = $data['price'] * 100; return $data; }}
As you can see, in the beforeFill()
, we divide by 100, and in the beforeSave()
, we multiply back. Again, this behavior is similar to Eloquent Accessors, just in Filament syntax.
Now, our Edit form looks/works correctly!
With this lesson, I wanted to show you an example of how to modify fields before/after saving them and when showing them in the table.