How to: re-use historical user input/selections to populate form controls

By | November 25, 2020

What if you wanted to populate model-driven app form controls based on the previous selections made by the same user? To give you a specific example: let’s say there is a location field on the form, and let’s say our user can travel between multiple locations. In both locations, this user is going to work at the front desk, where there is a desktop computer.

How do we only ask the user to provide location selection once on each of those desktops?

Here is a simplified version – notice how “Location” is empty the first time I’m creating the invoice. Then it keeps using “Toronto” by default:

default

I’m sure there could be different ways to do it, but here is one option:

  • We need a javascript function that executes on load of the form and reads stored values from the local storage
  • We need another function that executes on save of the form and saves attribute values to the local storage

And we just need to configure onload/onsave events of that form properly

So, here is the script:

var attributeList = null;

function loadAttributeValues(executionContext, attributes)
{	
	var formContext = executionContext.getFormContext();
	attributeList = attributes.split(",");
	if(attributeList == null) return;
	
	for(var i in attributeList)
	{
		let attrName = attributeList[i];
		if(formContext.getAttribute(attrName) != null
		   && formContext.getAttribute(attrName).getValue() == null)
		{
			try{
			formContext.getAttribute(attrName).setValue(JSON.parse(localStorage.getItem(attrName)));
			}
			catch{
			}
		}
	}
}

function storeAttributeValues (executionContext)
{
	var formContext = executionContext.getFormContext();
	for(var i in attributeList)
	{
		if(attributeList == null) return;
		let attrName = attributeList[i];
		if(formContext.getAttribute(attrName) != null)
		{
			let value = formContext.getAttribute(attrName).getValue();
			if(value != null) value = JSON.stringify(value);
			localStorage.setItem(attrName, value);
		}
	}
}

  • Here is how the form is set up:
  • OnLoad Event
  • image
  • image

  • OnSave Event

image

image

Both functions will use the same list of attributes, so I only need to provide that list to the onload function (and, of course, depending on how you want it to work and what you want it to do, you may have to change that).

Have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *