and frappe.ui.form.on usage


I’m trying to do something that seems on the surface to be very straightforward, but it’s proving to be more difficult than expected.

Basically, I have a python script in a custom app that I want to run every time a material request item is added, removed or modified. It modifies a custom field called “total”. This python script does not require any arguments, and does not return any data. I’m trying to run this python script and refresh the “total” field from a custom script attached to Material Request.

If I run my python script manually using “bench execute email_digest.scripts.calculate_totals”, it works perfectly, but that doesn’t help very much if I have to fire it manually every time.

This is what I have so far:

frappe.ui.form.on(“Material Request Item”,
method: “email_digest.scripts.calculate_totals”,
args: {},
callback: function() {refresh_field(total)}

I think I’ve spent about 8 hours trying to get this to work, and have been unsuccessful. Does anyone see what I’m doing wrong?

You need to make the call inside the button code.

    frappe.ui.form.on("Material Request Item", 
           //HERE THE CODE

@JamesE can you share the full script?

You need to call frm.set_value(fieldname, value) instead of refresh.

Your function email_digest.scripts.calculate_totals also needs to return the code

Share the full client side / server side script your have written.

Hey guys,

So I managed to sort out my own problem once I got my head around custom scripts. Turns out I didn’t even need the server-side script, it’s now handled entirely inside the custom script. Thanks for pointing me in the right direction! Here’s the end result, which calculates the total price of the order:

frappe.ui.form.on("Material Request Item", 
         price_in_gbp: function(frm) {
         var grand_total = 0;
         $.each(frm.doc.items, function(i, d) { grand_total += d.price_in_gbp * d.qty; });
         frm.set_value("total", grand_total);

There’s one last issue with this script: it only updates when a new item is added. It does not update if an item is edited or removed. How would I add more triggers for material request items being edited or deleted?

1 Like