Dec 30, 2024
0
Level 13
Calculating and Updating Inputs on the fly
Hi. Im working on trying to get an invoicing system setup on a test app (more for learning) and I'm having an issue with the repeater field updating the subtotal input and the invoice_total, but also the discount. Theres an odd issue where the repeater returns an odd figure to the subtotal and then If i update anything else it disapears and throws an error saying that subtitle is empty. Any help or info would be great, cheers
Heres the resource code:
Section::make('Service/Product details')
->description('Details on the quantity, pricing and total costs.')
->columns(2)
->schema([
Forms\Components\Repeater::make('items')
->label('Invoice items')
->columnSpanFull()
->relationship()
->schema([
Forms\Components\TextInput::make('description')
->required()
->columnSpan(3),
Forms\Components\TextInput::make('price')
->numeric()
->inputMode('decimal')
->required()
->live()
->afterStateUpdated(function (Get $get, Set $set, $state) {
// Calculate total when price is updated
$qty = $get('qty'); // Get current qty
$set('total', $state * $qty); // Update total
})
->prefix('£'),
Forms\Components\TextInput::make('qty')
->numeric()
->required()
->live()
->afterStateUpdated(function (Get $get, Set $set, $state) {
// Calculate total when qty is updated
$price = $get('price'); // Get current price
$set('total', $price * $state); // Update total
}),
Forms\Components\TextInput::make('total')
->label('Total')
->numeric()
->inputMode('decimal')
->disabled() // Make it read-only
->dehydrated()
->prefix('£'), // Prevent it from being saved directly
])
->afterStateUpdated(function (Get $get, Set $set) {
// Calculate the invoice total whenever items change
$items = $get('items');
$invoiceTotal = collect($items)->sum('total');
$set('subtotal', number_format($invoiceTotal, 2));
})
->live()
->addActionLabel('Add invoice item')
->columns(6),
Grid::make(1)
->schema([
Forms\Components\TextInput::make('subtotal')
->numeric()
->live()
->inputMode('decimal')
->disabled()
->dehydrated()
->default(0)
->prefix('£'),
Forms\Components\TextInput::make('discount')
->label('Discount')
->numeric()
->reactive()
->inputMode('decimal')
->default(0)
->suffix('%')
->afterStateUpdated(function (Get $get, Set $set, $state) {
$subtotal = $get('subtotal');
$discount = $state / 100;
$total = $subtotal - ($subtotal * $discount);
$set('invoice_total', number_format($total, 2));
}),
Forms\Components\TextInput::make('invoice_total')
->label('Invoice Total')
->numeric()
->live()
->inputMode('decimal')
->disabled()
->dehydrated()
->default(0)
->prefix('£'),
])->columnStart(2),
]),
Please or to participate in this conversation.