I'm working on this project and whenever I change the value PHP the total amount of usd should also be updated in real time
As you can see, when I changed the PHP, the total amount usd should be 2 and total amount php should be 100 and I'm getting the old data of total amout of both usd and php. I'm using afterStateUpdated so everytime the USD or PHP changes, the Total amount USD and PHP should be updated too.
Hidden::make('clicked_field')->default(true),
Repeater::make('particulars')
->relationship('particular')
->schema([
TextInput::make('amt_usd')
->required()
->numeric()
->label('USD')->suffix('USD')
->live(debounce: 600, onBlur: true)
->afterStateUpdated(function ($state, callable $set,
callable $get) {
$set('../../clicked_field', true);
$exRate = $this->data['ex_rate'] ?? 0;
$amt_php = $state * (float) $exRate;
if ($state === 0) $amt_php = 0;
$set('amt_php', round($amt_php, 2));
self::updateTotals($set, $get);
})
->extraInputAttributes(['class' => 'text-right'])
->reactive()
->columnSpan(1),
TextInput::make('amt_php')
->required()
->numeric()
->label('PHP')
->suffix('PHP')
->live(debounce: 600, onBlur: true)
->extraInputAttributes(['class' => 'text-right'])
->afterStateUpdated(function ($state, callable $set,
callable $get) {
$set('../../clicked_field', false);
$exRate = $this->data['ex_rate'] ?? 0;
if ($state === 0) $amt_php = 0;
$amt_usd = $state / (float) $exRate;
$set('amt_usd', round($amt_usd, 2));
self::updateTotals($set, $get);
})
->columnSpan(1),
])
->columns(6)
->columnSpan(6)
->live(debounce: 600, onBlur: true)
->addActionLabel('Add Particular')
->afterStateUpdated(function ($state, callable $set, callable
$get) {
self::updateTotals($set, $get);
})
])->label('Particulars'),
private static function updateTotals(callable $set, callable $get): void
{
$particulars = $get('particulars') ?? [];
$exRate = $get('ex_rate') ?? 0;
$freshParticulars = $particulars;
$totalUsd = collect($freshParticulars)->sum(fn ($item) => (float)($item['amt_usd'] ?? 0));
$totalPhp = collect($freshParticulars)->sum(fn ($item) => (float)($item['amt_php'] ?? 0));
switch($get('clicked_field')){
case true:
$set('billed_dollar', round($totalUsd, 2));
$set('billed_peso', round($totalUsd * $exRate, 2));
break;
case false:
if ($exRate != 0) {
$set('billed_dollar', round($totalPhp / $exRate, 2));
}
$set('billed_peso', round($totalPhp, 2));
break;
}
}
What I did is to kinda track if the field I'm clicking is USD or PHP, but still I can't achieve my goal which is to update the total amounts of usd/php whenever there are changes for both USD and PHP
How do I prevent getting the previous data? because I also notice that the data that the updateTotals are getting is the old one.