Fetch the last row of child table and update field in main doc type

Dear Forum
I have a doctype named Trips with child table called Tracking. The child table has many rows with fields Milestone, Date and Comment as shown in attached picture. I would like to update the fields Milestone, Updated on and Comment on main doctype using data from the last row of the child table. Every time there is an addition in child table row, the values in main doctype field should change to fetch data from the last row. Please help me write a script that can do this job.

Dear @ganureddy I appreciate your response. Could you please further elaborate the code , maybe using actual field names. Thank you.

Hi @lchigwanda,

Please check the syntax.

frappe.ui.form.on('Parent Doctype', {
    refresh: function(frm) {
        // Add a custom button or trigger this code on a specific event
        frm.add_custom_button(__('Update Last Value'), function() {
            // Get the last row from the child table
            var lastRow = frm.doc.child_table_name.slice(-1)[0]; // Replace 'child_table_name' with the actual name of the child table

            if (lastRow) {
                // Get the value from the last row
                var lastValue = lastRow.field_name; // Replace 'field_name' with the actual field name in the child table

                // Set the value in the parent doctype
                frm.set_value('field_name_in_parent', lastValue); // Replace 'field_name_in_parent' with the actual field name in the parent doctype
                frm.refresh_field('field_name_in_parent'); // Refresh the field in the parent doctype
            } else {
                frappe.msgprint(__('No rows found in the child table.'));
            }
        });
    }
});

Please set your doctype name, child table field name, and parent field name and reload and check it.

I hope this helps.

Thank You!

2 Likes

Thank you. It worked!!