Calling code/script from a Rule

Rules are a quick way to add dynamic functionality to a form, so a lot of programmers choose to use rules even when they know how to write the code to do the same thing. However, sometimes after writing a complex set of rules they may realize that they need to do something rules doesn’t support, and we know they don’t want to rewrite all their rules in code just to add that one little bit.

Alas, there’s no rules action type for “Call code”, but there is a roundabout way to call your code anyway.

Let’s say you have the following function in your form template:


VBScriptFunction Test(param) XDocument.UI.Alert("Param: " & param) Test = trueEnd Function Jscriptfunction Test(param) { XDocument.UI.Alert("Param: " + param); return true;}
VB.NetPublic Function Test(ByVal param As String) As Boolean thisXDocument.UI.Alert("Param: " & param) Test = TrueEnd Function C#public boolean Test(string param) { thisXDocument.UI.Alert("Param: " + param); return true;}

You can call that function from the condition of a rule by using the xdExtension namespace.

For example, here’s how to call the function from a rule when the form is opened:

  1. Click Form Options on the Tools menu.
  2. On the Open and Save tab, click Rules.
  3. Click Add, name the rule, and then click Set Condition.
  4. Select The expression in the first drop-down list, and then enter: xdExtension:Test(“foo”)
  5. If you want the function to be conditional, then put the condition before the function call with an AND clause. For example, to get if foo>bar, then Test(“foo”) , use foo>bar and xdExtension:Test(“foo”) . (This is possible because conditions are evaluated using short-circuit boolean evaluation. In other words, they are evaluated one clause at a time, and if the first clause determines the result, then the rest of the conditions are “short circuited” and don’t get executed.)
  6. The Rule dialog box requires at least one action, but if you don’t have any actions to run in that rule, you can click OK if you select the Stop processing rules when this rule finishes checkbox. To avoid actually stop processing rules, make your condition always return false. For example: xdExtension:Test(“foo”) and false (“false” here is actually looking for the node named “false” which doesn’t exist, so returns the empty set, which is translated to false(). You could just as easily use “foobar” or anything else.)

Finally, extract your form files and add the following attribute to the manifest.xsf file’s xDocumentClass element:

xmlns:xdExtension="http://schemas.microsoft.com/office/infopath/2003/xslt/extension"