How to add customize the Update Cost function in BOM

Hello team,

I have created a custom field for calculating the Unit Production Cost of a BOM. I have a client script that triggers every time the Total Cost is updated on the form.

Everything works fine, except when the Total Cost is updated by the "Update Cost’ button or automatically through a scheduled task.

image

How can I update my custom field every time the Total Cost is updated for the BOM, whether by a custom button action or as a scheduled task?

Hi @Abhishek_Agarwal,

Hmm :thinking:,

You can use to update your custom field for calculating the Unit Production Cost of a BOM:

frappe.provide("frappe.model");

frappe.ui.form.on("BOM", {
    // This function is called whenever the Total Cost field is updated
    total_cost: function(frm, cdt, cdn) {
        // Get the total cost and quantity from the BOM
        var total_cost = frm.doc.total_cost;
        var qty = frm.doc.qty;

        // Calculate the unit production cost
        var unit_production_cost = total_cost / qty;

        // Set the value of your custom field
        frappe.model.set_value(cdt, cdn, "unit_production_cost", unit_production_cost);
    }
});

With this script, your custom field for the Unit Production Cost should be updated automatically every time the Total Cost field is updated, whether it’s done manually or through a scheduled task.

I hope this helps.

Thank You!

Hi @NCP,

Thanks for your help. This is the code I’m using currently:

frappe.ui.form.on('BOM', {
	total_cost(frm){
	    var base_tot_cost = frm.doc.total_cost * frm.doc.conversion_rate;
	    var final_qty = frm.doc.quantity - frm.doc.process_loss_qty;
	    var cost_unit = frm.doc.total_cost / final_qty;
	    var base_cost_unit = base_tot_cost / final_qty;
	
	frm.set_value({
        unit_cost: cost_unit,
        base_unit_cost: base_cost_unit
        });
	},

	before_save(frm){
	    frm.trigger('total_cost');
	}
})

It works fine when I’m editing the BOM - but doesn’t update values if the total_cost changes via code (custom button or task).

How is set_value through frappe.model different from how I was doing it? Sorry if it’s a dumb question, I’m new to ERPNext customization.

Best,
Abhishek

can you apply the script and check or not?

Hi,

Applied the script you provided.
It works when the form is edited manually.
Does not work when the total_cost is updated via the Update Cost button.

If you set the code in the Update Code button, the base functionally related script will not work.
So I suggest that you, please add a custom button on the page and apply the script your according.

Thank You!

I understand, but then it will not update automatically on a schedule, like the default functionality.

I was hoping to get a way to hook the existing custom button. Not sure if that’s possible?

Add custom button in form:

Reference:

Please check it.