# Sum or Product of Fields

How do I write a custom code that:1.
Calculates the Product of two fields in the same document (Stock Entry
Detail). Let’s say we are trying to calculate the Net Weight of an Item
times the quantity. Let’s call it the Total Item Weight

Calculates the sum of the the same field (Total Item Weight) for all
items in a particular Stock Entry document to return the Total Weight of
all items in that Stock Entry…

It would have been simple if the UOM was KG, but the UOM is Nos.

The code will look like:

``````var calculate_net_weight = function(frm, cdt, cdn) {
var d = locals[cdt][cdn];
if (d.field1 && d.field2) {
d.net_weight = flt(d.field1) * flt(d.field2);
refresh_field('net_weight');
}

calculate_total_weight(frm);
}

var calculate_total_weight = function(frm) {
var total_weight = frappe.utils.sum(
(frm.doc.items || []).map(function(i) { return i.net_weight; })
);

frm.set_value("total_weight", total_weight);
}

frappe.ui.form.on("Stock Entry Detail", "field1", function(frm, cdt, cdn) {
calculate_net_weight(frm, cdt, cdn);
})

frappe.ui.form.on("Stock Entry Detail", "field2", function(frm, cdt, cdn) {
calculate_net_weight(frm, cdt, cdn);
}
``````

Thanks Nabin,

I used the following custom script to calculate the total item weight within the stock entry detail.

cur_frm.cscript.qty = function(doc, cdt, cdn) {

if (doc.net_weight && doc.qty) {
doc.total_item_weight = flt(doc.net_weight)*flt(doc.qty);
refresh_field(‘total_item_weight’);
refresh_field(“[table_field]”)
}
}

This is based on a few posts I saw here.

Is this right? It’s not working. I didn’t use the cur_frm.cscript.custom_field2 = cur_frm.cscript.custom_field1; bit at the end because field qty is not a custom field and is a standard field. Not sure if that’s right though.

Thanks

Jay

@JayRam did you ever get this working?

Yes I did. Need help? Or were you offering some?

Thanks

Jay

I’m trying to tie up some open threads in the Custom Script category is all.

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.

An example of your final solution would be a great addition to the Community Custon Script Wiki.