On my new form, I wish to execute further code that involves processing the ID of the item just created. Obviously the ID is not available before the item is saved, but I was hopeful I could get the ID once the window closed.
Alas, it does not appear to be the case. I don't want to get the ID of the previously added item and then add one to it. Any suggestions? It seems that the commit occurs even after the window closes. Is there a commit event that I can listen for?
In my example, there could be a disjoint in the processing of thisID, as it is populated in a detached async process, but that aside, no value of the latest ID is ever displayed in the console log either.
My code looks like this
var call = '$';
var thisID = '';
function MyPreSaveAction (){
// Set key field to be $ to capture it in the GetItemID function
window.addEventListener("unload", getID(), false);
return true;
}
function getID(){
var n = 0;
// Loop several times to see if the added item appears.. alas no, it doesn't
while (n < 20) {
n++;
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getItemID());
}
alert('Thank you for your request. Your receipt number is: '+thisID);
}
function getItemID(){
var context = new SP.ClientContext();
var list = context.get_web().get_lists().getByTitle('My List');
if (call == "$") { call = "#"} else { call = "$"} // Vary it in case it is a caching issue
var caml = new SP.CamlQuery();
caml.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name="Keyfield" /><Value Type="Text">'+call+'</Value></Eq><Eq><FieldRef Name="Author" LookupId="True"/><Value Type="Lookup">' + _spPageContextInfo.userId + '</Value></Eq></And></Where></Query><RowLimit>1</RowLimit></View>');
var listItems = list.getItems(caml);
context.load(listItems , 'Include(Title,ID)');
context.executeQueryAsync(function(){
var listEnumerator = listItems.getEnumerator();
while (listEnumerator.moveNext()) {
// get the current list item.
var listItem = listEnumerator.get_current();
// get the field value.
thisID = listItem.get_item('ID');
console.log('Created ID is '+ thisID);
};
},
function(){
});
}