How to Write a Frappe Client Script to Calculate and Display Total for a Child Table?

Hi everyone,

I’m working on a custom Doctype in Frappe called Construction Work Order. This Doctype includes a child table named Materials Table. Each row in the child table has a field called Amount (type: Currency), and I want to calculate the sum of all the Amount values across the rows in this table.

The calculated sum should then be displayed in a separate field in the main Doctype called Grand Total (type: Currency). Here’s what I’m trying to achieve:

  1. Dynamically update the Grand Total field whenever:
  • A row is added, updated, or removed from the Materials Table.
  • The Amount field in any row is modified.
  1. Ensure the calculation is performed on the client side (using a Client Script) for real-time updates.

I’ve tried writing some scripts, but I’m struggling to get it working correctly. Can anyone help me write a proper Client Script to achieve this functionality?

Thanks in advance for your guidance!

Assuming the child table field name in parent is “work_item” and grand total field name is “grand_total”, try the following

frappe.ui.form.on("Construction Work Order", {
    refresh(frm){
        calculate_grand_total(frm)
    },
})
frappe.ui.form.on("Materials Table", {
    work_item_add(frm, cdt, cdn){
        calculate_grand_total(frm)
    },
    work_item_remove(frm, cdt, cdn){
        calculate_grand_total(frm)
    },
    amount(frm, cdt, cdn){
        calculate_grand_total(frm)
    }
})
function calculate_grand_total(frm){
    var total = 0
    for (var row of frm.doc.work_item) {
        total += row.amount
    }
    frm.set_value("grand_total", total)
    frm.refresh_field("grand_total")
}

(P.S. Typed it out on a mobile, so please debug for syntax and other issues)