ERPNext Conference 2019* ERPNext.com Blog

Calculate and set value of a field based on IF-ELSE conditions on multiple fields

customization
script
custom_script
erpnext
frappe

#1

Hi,

I have 4 fields as below in a DocType called “Delivery”

  1. delivery_region (Field type: Select | Options: North, South)
  2. delivery_node (Field type: Select | Options: Inward, Outward)
  3. delivery_base (Field type: Float)
  4. delivery_charges (Field type: Data, read-only)

I want to calculate “delivery_charges” based on the below 4 conditions depending upon the values selected in “delivery_region” and “delivery_node” fields

The 4 conditions for “delivery_region” and “delivery_node” are as below:

  1. North & Inward: “delivery_node” = “delivery_base” x 1.5
  2. North & Outward: “delivery_node” = “delivery_base” x 2.5
  3. South & Inward: “delivery_node” = “delivery_base” x 3.5
  4. South & Outward: “delivery_node” = “delivery_base” x 4.5

The “delivery_charges” field should be auto-calculated as the above 4 conditions.

I have written the following custom script but it is not working

frappe.ui.form.on("Delivery", "delivery_base", function(frm) {

    if (frm.doc.delivery_region == "North" && form.doc.delivery_node == "Inward") {
        frm.set_value("delivery_charges", flt(frm.doc.delivery_base) * 1.5);
    }
    else if (frm.doc.delivery_region == "North" && form.doc.delivery_node == "Outward") {
        frm.set_value("delivery_charges", flt(frm.doc.delivery_base) * 2.5);
    }
    else if (frm.doc.delivery_region == "South" && form.doc.delivery_node == "Inward") {
        frm.set_value("delivery_charges", flt(frm.doc.delivery_base) * 3.5);
    }
    else if (frm.doc.delivery_region == "South" && form.doc.delivery_node == "Outward") {
        frm.set_value("delivery_charges", flt(frm.doc.delivery_base) * 4.5);
    }
});

Any help will be appreciated.

Thanks :slightly_smiling_face:


#2

In place of form.doc.delivery_node it should be frm.doc.delivery_node


#3

I fixed it after posting, but its still not working.


#4

Is delivery doctype is child doctype in some another doctype?


#5

Hi, its working now. Typo error of frm.doc.delivery_node was the mistake.
I had to reload the page to get it to work correctly.

Thanks :grin: