InfoPath - abusing a secondary datasource as temporary variable
This is an InfoPath technique that I've recently started using, and is pretty awesome.
Problem:
- InfoPath is great with rules and fields, but modifying the field means that your form has now changed. In code behind we have formstate variables, but they are not visible by InfoPath rules.
- We may want to change these fields in later versions of the template.
- If only we can have temporary variables to use in InfoPath
Solution in one sentence:
- Create a secondary datasource,
useabuse it to hold variables that you don't want to save to your main form
Real Example
How to detect if your form has been changed by the user since it was opened. This is a tweaked version of Alec Pojidaev's How to check if your InfoPath form is “dirty”? (Tracking changes) using secondary temporary variables.
Steps
- Create a separate secondary datasource
- Add the XML file as a secondary datasource
- Now we have a secondary data source that we can use
- Use that datasource to keep all the "UI" logic. Such as:
- "a checkbox to confirm whether I want to save and close, or just close"
- A rich text field to show a message that I display on a separate message View
- Various validation or toggle Booleans to control the UI
- Because the secondary datasource is not saved back to the main datasource, changes to the secondary datasource tree can be considered "discarded", effectively giving us "temporary variables" that rules can use.
- Create the form rules
- Set the field "Form" on the secondary data source to that of the current main datasource
- To test if the current form, at a later point in time, is the same as the form when it was opened
Demo
- On open, is the form the same as when we opened?
- After some changes
- Delete our changes - "true" again
How to use it
- When a form is opened, use rules (or code) to set the default values in the secondary datasource
- Through the lifetime of the form you can set the values to whatever you want, and use it in conditions
- When the form closes it doesn't get saved
Benefits
- You can track UI logic without actually modifying the main form
- You can then use the string(.) trick to save the current form on form-load, then use that value to compare with the form at a later date to see if the form had been changed by the user
- Some values, like "current user displayname" can be stored temporarily and is perfect for this
- If you didn't like a temporary variable, just remove them or rename them. Because they are not saved to the main data source, you don't have to worry about breaking existing or future forms.