Script queries for empty fields
By Lars Mäurer on 25. Oktober 2023
BeginnerTask: A script should be written that tests whether a certain field is empty.
The example here is the “user” field.
The query could look like this:
if (frm.doc.user === "") {...}
This way you test whether the field is empty. At least that's the idea.
The following problem occurs:
In every newly created document, all the fields that are empty and have not yet been touched have not yet been created in the background. This also affects empty fields when duplicating documents, etc.
NOTE: You can see the fields in the document (empty), but the variables themselves do not exist until then.
If you fill out such a field and then delete the entry, it will look the same in the document. But now the variable exists and is empty. In the case of a script that is supposed to test whether the field is empty, there will be problems.
In our example case the test will not work correctly, I have tested this several times: the query...
frm.doc.user === ""
...results in "FALSE" because the field does not yet exist, and a non-existent field cannot be compared with anything.
If you fill out the field, save it, delete it again and save it, then the query works because the field at least exists.
Solution:
The query must be formulated in reverse:
// here's how it works:if (!frm.doc.user){...}// this is a kind of short form of:// if (!frm.doc.user !== ""){...}// here's the old version again:// if (frm.doc.user === ""){...}
Basically this is actually the same thing (negated twice), but interestingly (in the case of variables that don't yet exist) this works.
If the variable does not exist, then "!frm.doc.user" is true. It's not particularly intuitive, but it works!!
Conclusion:
With this reverse query you can simultaneously test whether a variable is even there - and - whether it is empty.
Yay!
Have fun with this little trick - if it ever plays a role. :-)
Weitere Artikel zum Automation