I want to fetch the values of a child table and display it in another doctype

First Doctype - Motor
Second Doctype - Policy
Child table - insurer_child
Child table fields - insurer_name, to, cc, bcc
Note: insurer_name is linked to a master called insurer, Common ID in both Motor and Policy doctypes is ProspectID

Once the child table is saved in Motor Doctype, the data in the child table should be displayed in policy doctype which also contains the same child table… Also, this functionality should happen only for the same Prospect ID
Please send me a code which can attain this functionality. Thanks in advance.

Create a custom script for the “Policy” doctype.

frappe.ui.form.on("Motor", {
    insurer_child_add: function(frm, cdt, cdn) {
        var child_row = locals[cdt][cdn];
        frappe.call({
            method: "fetch_child_table_values",
            args: {
                prospect_id: frm.doc.ProspectID
            },
            callback: function(response) {
                frm.clear_table("insurer_child");
                var fetched_rows = response.message;
                for (var i = 0; i < fetched_rows.length; i++) {
                    var new_row = frappe.model.add_child(frm.doc, "insurer_child", "insurer_child");
                    frappe.model.set_value(new_row.doctype, new_row.name, "insurer_name", fetched_rows[i].insurer_name);
                    frappe.model.set_value(new_row.doctype, new_row.name, "to", fetched_rows[i].to);
                    frappe.model.set_value(new_row.doctype, new_row.name, "cc", fetched_rows[i].cc);
                    frappe.model.set_value(new_row.doctype, new_row.name, "bcc", fetched_rows[i].bcc);
                }
                refresh_field("insurer_child");
            }
        });
    }
});

Create a server-side script to fetch the child table values

import frappe
@frappe.whitelist()
def fetch_child_table_values(prospect_id):
    child_table_values = frappe.get_all("Motor",
        filters={"ProspectID": prospect_id},
        fields=["insurer_child.insurer_name", "insurer_child.to", "insurer_child.cc", "insurer_child.bcc"],
        as_list=True
    )
    rows = []
    for value in child_table_values:
        row = {
            "insurer_name": value[0],
            "to": value[1],
            "cc": value[2],
            "bcc": value[3]
        }
        rows.append(row)
    return rows

Hi Prashant,

Thanks for the reply first… I have input your code, but still the child table does not fetch the value in Policy for the same Prospect ID after saving the Motor doctype… I think the reason might be that the child table values are not stored in the Motor doctype… Can you please check and let me know asap?? Thanks again.