Customize forms with client scripts
A client script is JavaScript that runs in the browser when a user works with a form or a list. Use it when Customize Form cannot do what you need. For example, a client script can filter the options of a field based on another field, set values when a field changes, or check data before save.
This page is for developers and system managers who know JavaScript.
Prerequisites
- The System Manager role.
- Basic knowledge of JavaScript.
Create a client script
- Open the Client Script list, and select New.
- In DocType, select the DocType, for example Sales Invoice.
- In Apply To, select Form or List.
- Write the script in Script.
- Select Enabled.
- Select Save.
- Reload the form to load the new script.
Write the script
A form script reacts to form events with frappe.ui.form.on. Each event gets frm, the current form.
frappe.ui.form.on("Sales Invoice", {
// Runs each time the form loads or reloads
refresh(frm) {
if (frm.doc.docstatus === 0) {
frm.set_intro(__("Check the due date before you submit."));
}
},
// Runs when the Customer field changes
customer(frm) {
frm.set_value("remarks", "");
},
// Runs before save. Throw an error to stop the save.
validate(frm) {
if (frm.doc.grand_total <= 0) {
frappe.throw(__("Grand Total must be more than zero."));
}
},
});Common events are setup, onload, refresh, validate, before_submit, and the name of any field, which runs when that field changes.
For child table rows, use the child DocType and the row event, for example frappe.ui.form.on("Sales Invoice Item", { qty(frm, cdt, cdn) { ... } }).
For the full API, read the Frappe Framework form scripting documentation.
Things to know
- Client scripts run in the browser. A user can bypass them, so do not rely on them for security or for data rules that must always hold. Use a server script or an app for those.
- If a change does not appear, reload the page without the browser cache: press Ctrl + Shift + R (Cmd + Shift + R on a Mac).
- Server scripts are a separate feature, written in Python. Read the Frappe Framework documentation on server scripts.