Prefill data in Multi Row Variable Sets
Hi,
In this article, I will share a code snippet on how to auto populate a multi variable set based on a specific value in the record producer.
In my example, based on a field change in record producer I want to fetch the entries from the database and prefill them in the multirow variable set.
Client Script
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
var ga = new GlideAjax('MyScriptInclude');
ga.addParam('sysparm_name', 'getItems');
ga.addParam('sysparm_type', newValue);
ga.getXML(parseData);
function parseData(response) {
var answer = response.responseXML.documentElement.getAttribute('answer');
var oDetails = JSON.parse(answer);
var my_varset = g_form.getField("my_multirow_varset"); //get your multivarset
for(var sKey in oDetails){
if (sKey == "my_multirow_varset") {
g_form.setValue(sKey, oDetails[sKey]); //This will set the multirow once the key is matched.
} else if (sKey == "total_rows") {
//sets the max rows to the available count, bcoz of which the add button will be disabled. you can also set max_rows_size=0 to disable add.
my_multirow_varset.max_rows_size = oDetails[sKey];
}
}
if(answer == 0) {
//No data for this Type. So hide the multirow var set
g_form.addInfoMessage('There are no Items for this Type '+newValue);
g_form.setVisible('my_multirow_varset',false);
}
}
}
Script Include
var MyScriptInclude = Class.create();
MyScriptInclude.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getItems: function(){
var itemID = this.getParameter('sysparm_type');
var oDetails = {};
var aDetails = [];
oDetails = new MyScriptInclude().getAllDetails(itemID);
aDetails = [{
"total_rows": oDetails["total_rows"],
"my_multirow_varset": JSON.stringify(oDetails["my_multirow_varset"])
}];
return JSON.stringify(aDetails[0]);
},
getAllDetails: function(itemID){
var oDet = {};
var aDet = [];
var total_rows=0;
var grItem = new GlideRecord("mytable");
grItem.addQuery('u_item_id', itemID);
grItem.query();
while(grItem.next()){
total_rows++;
oDet = {"type": grItem.u_type+ "",
"title": grItem.u_title+ "",
"description": grItem.short_description+ "",
"in_stock": grItem.u_stock+ "",
"supervisor": grItem.u_manager+ "",
"item_number": grItem.u_number+ ""
};
aDet.push(oDet);
}
return {"total_rows": total_rows, "my_multirow_varset": aDet};
},
type: 'MyScriptInclude'
});
To disable edit and delete icons, make the multirow variable set readonly.
You can create a ui policy and can make it readonly or from the client script, you can do it
g_form.setReadOnly('my_multirow_varset',true);
To disable Add button, you can call
my_multirow_varset.max_rows_size=0;
Let me know if you have any questions in the comments below.
Mark the article as helpful and bookmark if you found it useful.
https://www.servicenow.com/community/developer-articles/prefill-data-in-multi-row-variable-sets/ta-p/2298269