Client script examples
Each example is a complete client script. Create a client script for the DocType in the example, paste the code, and change the DocType and field names to yours.
Filter the options of a Select field
A Lead has two Select fields: State and City. The script shows only the cities of the selected state.
DocType: Lead. Custom fields: state and city.
const CITIES = {
Karnataka: ["Bangalore", "Mysore"],
Maharashtra: ["Mumbai", "Pune"],
};
frappe.ui.form.on("Lead", {
state(frm) {
const cities = CITIES[frm.doc.state] || [].concat(...Object.values(CITIES));
frm.set_df_property("city", "options", ["", ...cities]);
frm.set_value("city", "");
},
});Filter a link field in a child table
The Items table of a Sales Order offers only the items of one item group.
DocType: Sales Order.
frappe.ui.form.on("Sales Order", {
setup(frm) {
// "item_code" is the link field, "items" is the table field
frm.set_query("item_code", "items", function (doc, cdt, cdn) {
return {
filters: [["Item", "item_group", "=", "Products"]],
};
});
},
});A filter set with frm.set_query takes priority over a filter set in Customize Form.
Fetch a value into a child table row
When a user selects a batch in a Sales Invoice item row, the script copies the batch's expiry date into the row.
DocType: Sales Invoice. Custom field: expiry_date (Date) in Sales Invoice Item.
frappe.ui.form.on("Sales Invoice Item", {
batch_no(frm, cdt, cdn) {
const row = locals[cdt][cdn];
if (!row.batch_no) {
frappe.model.set_value(cdt, cdn, "expiry_date", null);
return;
}
frappe.db.get_value("Batch", row.batch_no, "expiry_date").then((r) => {
frappe.model.set_value(cdt, cdn, "expiry_date", r.message.expiry_date);
});
},
});TIP
For a field of the main form, you do not need a script. Use the Fetch From property. Read Fetch values from a linked document.
Build the item code from the item group and brand
The script builds the code of a new Item from its item group and brand, before the first save. For example, item group "Test A" and brand "Brand B" give TABB.
DocType: Item. The item code must be set by the user in your setup, not by a naming series.
const GROUP_CODES = { "Test A": "TA", "Test B": "TB" };
const BRAND_CODES = { "Brand A": "BA", "Brand B": "BB" };
frappe.ui.form.on("Item", {
validate(frm) {
if (!frm.is_new()) return;
const group = GROUP_CODES[frm.doc.item_group] || "XX";
const brand = BRAND_CODES[frm.doc.brand] || "BX";
frm.doc.item_code = group + brand;
},
});Two items with the same group and brand get the same code, and the second save fails. Add a number to the code if you need unique codes, or use a naming series.