Typical mistakes in formulas
The following sections summarize some typical mistakes and inefficiencies in formulas.
Include tokens in quotes
Do not forget that template tokens like {!name} are not JavaScript variables. They are replaced by actual values before being sent to the JavaScript engine. While numeric values can be used as is, strings are typically enclosed in quotes to form a meaningful result.
| Original Formula | Parsed Results | Comments |
|---|---|---|
counter += {!amount}; counter += 100;
|
Correct | You can treat numerical tokens as variables. |
if ({!country#code} == "US") If (CA == "US")
|
JavaScript error | CA variable does not exist. |
if ("{!country#code}" == "US") If ("CA" == "US")
|
Correct | You must always enclose string tokens in quotes or make them a part of larger string. |
Unnecessary quotes
You can often use the fact that template tokens will be replaced with real, non-quoted values to your advantage by simplifying token concatenation. You don't have to use JavaScript to concatenate tokens - the template parser can do it for you.
| Formula | Comments |
|---|---|
var ln = "{!lastName}";
var fn = "{!firstName}";
return ln+", "+fn; var ln = "Ellison";
var fn = "John";
return ln+", "+fn;
|
Correct but inefficient |
return "{!lastName}, {!firstName}"; return "Ellison, John";
|
Correct and efficient |
Avoid loops in formulas
Although you can use template loops in formulas, be aware that they can result in very long JavaScript after parsing; that script could be aborted by Platform due to formula length and execution time limitations. Consider this example:
{!#LOOP_BEGIN.R12345}
// Do some processing
rbv_api.setFieldValue(...);
{!#LOOP_END.R12345}
The code inside the loop will be replicated for each record in the loop. A much more efficient approach would be to use a JavaScript for() loop:
var ids = rbv_api.getRelatedIds("R123456", {!id});
for (var i=0; i<ids.length; i++) {
var ordered = ids[i];
rbv_api.runTrigger("order", orderId, "trUpdate");
}
In this example, the formula obtains a list of related IDs, loops through them all and invokes a trigger on the corresponding related record. You may also use Query API to extract data instead of loops through data records. Warning: If a number record in a loop is large you may hit timeout limit for formula execution.
Using Comments
You can use valid JavaScript comments in your formulas. However please keep in mind that:
- Comments enlarge total length of formula and may potentially lead to hitting limit on overall formula length.
- Avoid using
//-style comments since they may lead to error should carriage-return in your formula accidentally be lost. Use the/* */style for comments in JavaScript formulas.