I just learned something very interesting while answering a forum thread just now which I thought I should share with the rest of you.
In all the scripts I’ve written so far, I had never realized this simple rule: When writing calculation scripts to set the value of certain fields, the line in your script which assigns a value to the field on which the Calculate event was fired should *always* be the *last line* in your script. This is because the last-executed line in your script is the one that the XFA Object Model will use to determine the value of that field.
While it’s generally not recommended to do much more than set a field’s value in the Calculate event, reality is that most of us use it for much more than that: Since it fires on all fields on a form after a field’s value changes, we may use it to affect the presence, color, dimension, etc., of some fields which depend on the values of other fields. Therefore, it’s very easy to fall into this trap where your calculation script isn’t working probably simply because you haven’t structured it correctly.
Take the following FormCalc script as an example:bc. if (NumericField1 > 0) thenNumericField1 * 10;$.presence = “visible”;else0;$.presence = “invisible”;endifThis scripts runs in the Calculate event of a numeric field and, if NumericField1’s value is greater than zero (0), results in the field becoming visible and its value set to the product of NumericField1’s value multiplied by 10. If NumericField1’s value is zero (0) or less, its value is set to zero (0) and it becomes invisible. Note the _order_ of the lines which set the field’s value and the ones which set its presence: The value is set _before_ the presence is set.The result of this script is that the presence is affected properly depending on the value of NumericField1 however, since the last-executed line is “$.presence = ‘visible'” (or “invisible”), the value acutally assigned to the field is “visible” (or “invisible”) which evaluates to “0” as a numerical value. Therefore, with this script, the value of the product field would always be zero (0).If you change the order of the lines which set the field’s value and presence as follows:bc. if (NumericField1 > 0) then$.presence = “visible”;NumericField1 * 10;else$.presence = “invisible”;0;endifThen both the field’s presence and value will be set correctly because the last-executed lines in each block are the ones which set the field’s calculated value.