ERPNext销售发票自定义脚本问题:修改行项目金额计算逻辑
Hey there, let's figure out why your custom script isn't working and fix it up!
First, the main issue with your original code is the incorrect parameter order in frappe.model.set_value. This function expects arguments in the order: (doctype, docname, fieldname, value)—you had the fieldname first, which is why the value wasn't being set correctly.
Here's the corrected version of your script, and I've also added triggers for qty and rate fields so the amount updates whenever any of the three relevant fields change:
frappe.ui.form.on("Sales Invoice Item", { custom_field: function(frm, cdt, cdn) { calculate_amount(frm, cdt, cdn); }, qty: function(frm, cdt, cdn) { calculate_amount(frm, cdt, cdn); }, rate: function(frm, cdt, cdn) { calculate_amount(frm, cdt, cdn); } }); function calculate_amount(frm, cdt, cdn) { let d = locals[cdt][cdn]; // Calculate the amount using your formula let calculated_amount = d.rate * d.qty * d.custom_field; // Correctly set the value using frappe.model.set_value frappe.model.set_value(cdt, cdn, "amount", calculated_amount); // Optional: Refresh the field to ensure the UI updates immediately frm.refresh_field("items"); }
Let's break down what's changed:
- Parameter Order Fix: We now pass
cdt(doctype),cdn(docname), "amount" (fieldname), and the calculated value tofrappe.model.set_value—this is the correct syntax the function expects. - Reusable Calculation Function: I moved the amount calculation into a separate function
calculate_amountso we don't repeat code across different field triggers. - Additional Triggers: Added listeners for
qtyandratechanges, so the amount will update automatically if either of those fields are modified, not justcustom_field. - UI Refresh: The
frm.refresh_field("items")call ensures the Sales Invoice's items table updates right away to show the new amount.
One quick thing to double-check: make sure your custom_field is a numeric field (like Float or Int) in the Sales Invoice Item doctype—if it's a text field, the multiplication won't work as expected.
内容的提问来源于stack exchange,提问作者Zeinab Mohammed




