Calculating Total Fields from Child Table and Displaying in Parent Form

Hello ERPNext Community,

I hope you’re all doing well. I’m working on a form where I need to calculate the sum of certain fields in a child table and display the result in fields on the parent form. Here’s the scenario I’m facing:

Form Structure:

*Parent Form: Timesheets Computation
*Child Table: Timesheet Detail Computation
*Fields in Child Table:

  • awake_hrs (number of awake hours)
  • sleep_hrs (number of sleep hours)

Requirement:

  • I need to compute the total of awake_hrs and sleep_hrs for all rows in the child table and display the result in two parent fields:
    • total_awake_hours
    • total_asleep_hours

What I’ve Tried:

Here’s the script I’ve been working on:

frappe.ui.form.on(‘Timesheets Computation’, {

  • awake_hrs: function(frm, cdt, cdn) {*
  •    calculate_totals(frm);*
    
  • },*
  • sleep_hrs: function(frm, cdt, cdn) {*
  •    calculate_totals(frm);*
    
  • },*
  • timesheet_detail_computation_add: function(frm) {*
  •    calculate_totals(frm);*
    
  • },*
  • timesheet_detail_computation_remove: function(frm) {*
  •    calculate_totals(frm);*
    
  • }*
    });

function calculate_totals(frm) {

  • var total_awake_hours = 0;*

  • var total_asleep_hours = 0;*

  • if (frm.doc.timesheet_detail_computation && frm.doc.timesheet_detail_computation.length > 0) {*

  •    frm.doc.timesheet_detail_computation.forEach(function(row) {*
    
  •        total_awake_hours += parseFloat(row.awake_hrs || 0);*
    
  •        total_asleep_hours += parseFloat(row.sleep_hrs || 0);*
    
  •    });*
    
  • }*

  • frm.set_value(‘total_awake_hours’, total_awake_hours);*

  • frm.set_value(‘total_asleep_hours’, total_asleep_hours);*
    }

Issue:

The totals for awake_hrs and sleep_hrs are still showing as zero (0), even after trying different triggers and debugging with logs. I’ve checked that the field names are correct and everything else seems fine, but I’m unable to figure out why the totals are not displaying properly.

Could anyone assist me in identifying what might be causing this issue? Any insights on where my script could be improved or alternative approaches to calculate totals from a child table and display them in the parent form would be greatly appreciated.

Thank you in advance for your support!

dear @marabytes You are running the script and calculation on the main table. It must be in from child table.
instead of frappe.ui.form.on(‘Timesheets Computation’, { keep frappe.ui.form.on(‘Timesheet Detail Computation’, {

Hey thanks @ErpnextRaja let me try and revert. Cheers!

Reference: Sum fields in child table and show total in parent field - #2 by NCP