VAT calculation

Hello, I woud like to make two field reactive but on client side. On an application I'm moving to Filament v3, I need to have two fields: price_excl_vatand price_incl_vat . I agree that is not the bast way to store the information as there is a field vat_rate. When the user fill the field price_excl_vat the other field should be calculated based on the vat_rate, and if the user types into the price_incl_vat field, it should also calculate the exclusive vat price. This was done in javscript in the legacy application. I needs to replicate that. Using the ->live()->afterStateUpdated() method don't seems to works, if the connection is slow you miss some typed characters. Could I replicate this in javascript/AlpinJs) on my Resource Form? I first though that ViewField could helps but I need a global alipine js component to hold the logic that interracts with several fields. Do you have some ideas? Thanks in advance!
Solution:
Do you have debugmode enabled? That's why it'll be super slow. But also do: ->live() ->lazy() ->afterStateUpdated()...
Jump to solution
3 Replies
Solution
toeknee
toekneeβ€’2mo ago
Do you have debugmode enabled? That's why it'll be super slow. But also do: ->live() ->lazy() ->afterStateUpdated() it'll slow down the network requests for when finished basically
Tetracyclic
Tetracyclicβ€’2mo ago
If you wanted to stick to doing it all locally, rather than use ViewField, you could create your own custom PriceInput, based on the existing TextInput field, that combines the two fields and returns an array of the two prices. Then use Alpine in the view for that input to do the calculation. You can then save the individual prices to two hidden fields representing the properties on the model, and set them from your custom input with afterStateUpdated()
dissto
disstoβ€’2mo ago
Well it its simpliest form as a start you could do:
// assuming 19% vat hence * 1.19
TextInput::make('price_excl_vat')
->columnSpanFull()
->live(onBlur: true)
->afterStateUpdated(function (Set $set, $state) {
$set('price_incl_vat', number_format($state * 1.19, 2));
}),

TextInput::make('price_incl_vat')
->columnSpanFull()
->live(onBlur: true)
->afterStateUpdated(function (Set $set, $state) {
$set('price_excl_vat', number_format($state / 1.19, 2));
}),
// assuming 19% vat hence * 1.19
TextInput::make('price_excl_vat')
->columnSpanFull()
->live(onBlur: true)
->afterStateUpdated(function (Set $set, $state) {
$set('price_incl_vat', number_format($state * 1.19, 2));
}),

TextInput::make('price_incl_vat')
->columnSpanFull()
->live(onBlur: true)
->afterStateUpdated(function (Set $set, $state) {
$set('price_excl_vat', number_format($state / 1.19, 2));
}),
As always there is a million ways of achieving what you want. This is just one way and more of an illustration rather than the production ready solution πŸ˜‹
Want results from more Discord servers?
Add your server
More Posts