Custom script help on fetch_add

frappe.ui.form.on('Sales Invoice', 'before_save', function(frm) {
    cur_frm.add_fetch('shipping_address_name','zone','zone');
});

This code is supposed to fetch the zone field from shipping_address link field / doctype then drop it into the sales invoice zone field right before save correct? It’s not working properly on my instance and was wondering if I am missing something or misunderstanding syntax for cur_frm.add_fetch.

add_fetch gets triggered when the link field based on which value needs to be set is changed (shipping_address_name in your case), it probably doesn’t work on save. If you want to do something before save, try using frappe.db.get_value instead (yes, we have it in JS too). The right place for using frm.add_fetch is onload. Avoid using cur_frm (legacy).

Thanks @snv, advise was helpful.

This code block fetches the values but it returns the full object.

 frappe.ui.form.on('Sales Invoice', 'before_save', function(frm) {
    let z = '';
    z = frappe.db.get_value('Address', {'name':cur_frm.doc.shipping_address_name}, 'zone');
    console.log(z);
    frm.doc.zone = z;
});

Asking for help/advice on how to parse the object to just get the field value. This post from @nonpolarity gives me a clue but not sure how to proceed. Any help apprecaited.

 frappe.ui.form.on('Sales Invoice', 'before_save', function(frm) {
    frappe.db.get_value('Address', {'name': frm.doc.shipping_address_name}, 'zone')
    .then(response => {
        console.log(response);
        // do something with response here...
    });
});

After quite some time, I figured out this works. Thanks @snv for the tips

frappe.ui.form.on('Sales Invoice', 'before_save', function(frm) {
    frappe.db.get_value('Address', {'name':cur_frm.doc.shipping_address_name}, 'zone')
    .then(response => {
        // console.log(response);
        // console.log(response['message']['zone']);
        frm.doc.zone = response['message']['zone'];
    });
});
1 Like