Any Idea to run JS script on any/specific doctype?

hello i have many js scripts which does almost the same for many doctypes and it is not practical to develop and copy changes to these files and apply minor changes, so i was wondering if any better idea can be done like using one controller ctl.bundle.js or wildcard like “frappe.ui.form.on(”*“)”

thanks in advance

Hi @PyJumper,

If you want to apply the logic for mutiple doctype then apply it in the utils.js in your custom app. then add it in the bundle js.

hooks.py

app_include_js = "your_custom_app.bundle.js"

your_custom_app.bundle.js

import "./utils";

/public/js/utils.js

$(document).on('app_ready', function() {
	$.each(["Opportunity", "Quotation", "Supplier Quotation", 
		"Sales Invoice", "Delivery Note",  "Sales Order",
		"Purchase Invoice", "Purchase Receipt", "Purchase Order"], function(i, doctype) {
			frappe.ui.form.on(doctype, {
				refresh: function(frm) {
					// add you logic
				}
			});
	});
});

Migrate the site, and build the app.

6 Likes

thanks a lot, i was not sure about that :grinning:
if a field exist in doctype and not in another it is fine right ?

You can put your dynamic logic according to the scenario :wink:

1 Like

got it thanks again, here is a modified version if someone wondering

const DOCTYPES = {
    "SALES_INVOICE": "Sales Invoice",
    "PURCHASE_INVOICE": "Purchase Invoice",
    "SALES_ORDER": "Sales Order",
}

$(document).on('app_ready', function() {
    for(let k in DOCS) {
        const DOC = DOCTYPES[k]
        const METHODS = {
            setup: function(frm) {
                // add your logic

            },
            refresh: function(frm) {
                // if we want something to be for specific doctype only we can do lle this
                if(DOC === DOCTYPES.SALES_INVOICE) {
                    console.log(`refresh is on sales invoice`, frm);
                }
                if(DOC === DOCTYPES.SALES_ORDER) {
                    console.log(`refresh is on sales order`, frm);
                }
            },
        }

        // if we want to add handler for specific doctype
        if(DOC === DOCTYPES.SALES_INVOICE) {
            METHODS["custom_my_field_name"] = function(frm) {
                console.log(`custom field is on sales invoice`, frm);
            }
        }


        frappe.ui.form.on(DOC, METHODS);
    }
});
3 Likes