I have this script that returns a random record regardless if I’m on a form or a saved search. Works great but I know using try catch this way is not correct. What is a better way to resolve if I’m trying to get a form recordset or search recordset?
Random_Record();
try {
var records = search.getRecords();
}
catch (err) {
var records = form.getRecords();
}
var record = records[Math.floor(Math.random() * records.length)];
form.selectRecord(record);
I would use something like this:
if (typeof search !== 'undefined'){
var records = search.getRecords();
} else {
var records = form.getRecords();
}
This doesn’t address the corner case where search
exists but doesn’t contain any records, eg records.length == 0
.
I wouldn’t use record
in var record = ...
since that is a predefined value.
thank you that works well
Seeing some unexpected behavior upon further review.
If I run the script from the Scripts menu, works fine. But fails from a button on a custom layout.
As a test, I created a new script with a single line of code.
console.log(typeof search);
From Scripts menu, correctly returns object
From button on form, incorrectly returns undefined
This is on same search, same record, just running the script from menu vs button.
When you launch a script from a button, do you get any records when using search.getRecords()
?
no
console.log(typeof search);
var records = search.getRecords();
console.log(records.length)
from menu:
6/1/22, 5:53:57 PM / Project / TEST
object
250
from button:
6/1/22, 5:53:50 PM / Project / TEST
undefined
TEST: ReferenceError: Can’t find variable: search, line:(null)
Looks like the context the script runs is different. Something Brendan will be able to answer.