ERPNext Foundation ERPNext Cloud User Manual Blog Discuss Frappé* Donate

How load JavaScript code in All Doctype

customization

#1

I need to load JavaScript code in all doctyps to do some validation.
I try this but it is not working.

frappe.ui.form.on('*', 'onload', function(frm) {
    if (frappe.meta.has_field(frm.doctype, "company")) {
	frm.fields_dict['company'].get_query = function(doc) {
	return {
		filters: {
			"company": 'test company'
		}
	}
}
    }

#2

Do you have a custom app available? If so, you can add your script there and have it linked into any document by adding

to hooks.py

app_include_js = [
   "/assets/yourapp/js/yourscript.js",

place your script file in yourapp/public/js/yourscript.js

add to yourapp/public/build.json

{
    "js/yourscript.js": [
        "public/js/yourscript.js"
    ]
}

If you are looking for a reference, you can look into https://github.com/libracore/erpnextswiss/blob/master/erpnextswiss/public/build.json

The base code of your script is executed when the document is loaded. You can make use to the jQuery document ready function to be sure the form is available and then apply your filter.

Hope this helps…


#3

@lasalesi thanks for your fast reply.
I now already what did you say.

I need help with this :

The base code of your script is executed when the document is loaded. You can make use to the jQuery document ready function to be sure the form is available and then apply your filter.

Could you give some example?


#4

In your code, include something like (ref. https://www.w3schools.com/jquery/event_ready.asp)

$(document).ready(function(){
  if (frappe.meta.has_field(cur_frm.doctype, "company")) {
    cur_frm.fields_dict['company'].get_query = function(doc) {
      return {
	filters: {
		"company": 'test company'
	}
      }
    }
  }
});

#5

@lasalesi Is this code will work only in the first doctype or all of them?


#6

If you load the js globally, it will execute every time (add a console.log("…") to make sure it does). Then, it should be executed on every doctype, and once the form is loaded your function applied. Have a try and let us know if it works as expected…