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.
Mutate Value Before Creating
Filament has methods to modify the value between entering it in the form and saving it in the DB.
- Method
mutateFormDataBeforeCreate()
for Create forms - Method
mutateFormDataBeforeSave()
for Edit forms
They 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.
Format Value in Table Column
We will add two modifier methods: dividing the value by 100 and formating the value with a currency.
For re-calculating the value...