John Liu .NET

View Original

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, use abuse 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

  1. Create a separate secondary datasource
    image
  2. Add the XML file as a secondary datasource
    image
  3. Now we have a secondary data source that we can use
    image
  4. 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
  5. 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.
  6. Create the form rules
    image

  7. Set the field "Form" on the secondary data source to that of the current main datasource
    image
  8. To test if the current form, at a later point in time, is the same as the form when it was opened
    image

Demo

  1. On open, is the form the same as when we opened?
    image
  2. After some changes
    image
  3. Delete our changes - "true" again
    image

 

How to use it

  1. When a form is opened, use rules (or code) to set the default values in the secondary datasource
  2. Through the lifetime of the form you can set the values to whatever you want, and use it in conditions
  3. When the form closes it doesn't get saved

Benefits

  1. You can track UI logic without actually modifying the main form
  2. 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
  3. Some values, like "current user displayname" can be stored temporarily and is perfect for this
  4. 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.