Select to view content in your preferred language

Create Auto-ID in Survey123 with JS?

148
2
05-16-2024 08:40 AM
Smileyk_mdt
New Contributor

Hello,

I'm trying to create an auto incrementing UniqueID in Survey123 with Connect. I was surprised to learn that attribute rules are not honored by hosted feature layers that are not Enterprise. To get around this, I found a JS code. It will populate the UniqueID field with a '1' but it won't actually increment the number. It is an integer and I used it as a calculate question in Survey123 connect. Any ideas on if this is the correct logic?

 

 

 

 

function getUniqueID() {
	var url = "https://services1.arcgis.com/dKlvxNSUvl36IGMp/arcgis/rest/services/Seatbelt_Survey_Sites_Pilot_2024/FeatureServer/4/query";
	var params = {
		where: "1=1",
		outFields:"UniqueID",
		orderByFields: "UniqueID DESC",
		returnGeometry: false,
		f: "json"
	};

	var queryString = Object.keys(params).map(key => key + '=' +
	encodeURIComponent(params[key])).join('&');

	var xhr = new XMLHttpRequest();
	xhr.open("GET", url + "?" + queryString, false);
	xhr.send();

	if (xhr.status === 200) {
		var response = JSON.parse(xhr.responseText);
		if (response.features && response.features.length > 0) {
			var maxID =  response.features[0].attributes.UniqueID;
			return maxID + 1;
		} else {
			return 1; //start at 1 if no records exist
		}
	} else {
		return null;
	}
}

 

 

 

 

 

0 Kudos
2 Replies
MobiusSnake
MVP

A few things to consider here:

  • What will happen if two different users are capturing surveys at the same time?  Both of them will get the same maxID, meaning they'll submit the same unique ID.
  • Likewise, what if someone collects data but doesn't immediately submit, and continues collecting additional records?  They could have several records in their drafts/outbox with the same ID.
  • Will you have users collecting data offline?  If so, this approach won't work.
  • Will you have users from other organizations collecting data?  If so, they'll be restricted from using JS and this won't work for them.

One option that would address all of these is a scheduled post-process.  For example, with a Notebook you could do this:

  • Submit your record with a null Unique ID
  • Have your Notebook query records with null Unique IDs
  • Assign sequential IDs based on the previous maximum

Although this would mean that at any time you could have some records without Unique IDs, you could also filter your apps/maps to exclude those records until an ID is assigned.

0 Kudos
abureaux
MVP Regular Contributor

Little know fact, but you can pull objectID into your survey. So any editing/Inbox uses of the survey can have the unique objectId field included.

Pull the ObjectID of existing features into a Survey123 form

0 Kudos