Get MRVS Row Count onSubmit?

John Shores1
ServiceNow Employee
ServiceNow Employee

Oh...Community!

I have a use case where I need to count the number of rows that have been added to a MRVS (multi-row variable set) before the record is written to the DB.  I've tried a couple of ways (onChange, onSubmit) to capture the row count, but none have been successful so far. 

getRowCount() is not available to client scripts and since the data hasn't been written to a table yet, I can't leverage it.  Looking for other options to count the number of rows in the MRVS to pass to a workflow as a parameter.   I need to make a decision in the workflow based on whether 1 or more than 1 item is in the list.

Any suggestions?

Thanks for being awesome!!!

1 ACCEPTED SOLUTION

Jace Benson
Mega Sage

A MVRS is literally stored as JSON.  You can parse the JSON and get it's length.

e.g.

g_form.getValue('questions'); returns below
/*
"[
  {
    \"order\":\"100\",
    \"question\":\"What do you need help with?\",
    \"required\":\"Yes\",
    \"help_text\":\"\"
  }
]"
*/

So with that... you can literally just say run a script like so;

var mvrsValue = g_form.getValue('questions');
if(mvrsValue){//if it has a value
  var jsonObj = JSON.parse(mvrsValue);
  console.log('There are ' + jsonObj.length + ' rows);
} else { // if i recall correctly, .getValue returns null if empty
  console.log('No Rows');
}

View solution in original post

4 REPLIES 4

Jace Benson
Mega Sage

A MVRS is literally stored as JSON.  You can parse the JSON and get it's length.

e.g.

g_form.getValue('questions'); returns below
/*
"[
  {
    \"order\":\"100\",
    \"question\":\"What do you need help with?\",
    \"required\":\"Yes\",
    \"help_text\":\"\"
  }
]"
*/

So with that... you can literally just say run a script like so;

var mvrsValue = g_form.getValue('questions');
if(mvrsValue){//if it has a value
  var jsonObj = JSON.parse(mvrsValue);
  console.log('There are ' + jsonObj.length + ' rows);
} else { // if i recall correctly, .getValue returns null if empty
  console.log('No Rows');
}

Hi @Jace Benson 

Your script helped me today. Thanks
I have one query here. For Example

/*
"[
  {
    \"order\":\"100\",
    \"question\":\"What do you need help with?\",
    \"required\":\"Yes\",
    \"help_text\":\"\"
  }
]"
*/

Let's say I want to get the value of Order or Required field how can I get it from the above JSON??

 

Thanks,

Piyush Kumar

If you have the value as a string, you just need to parse the object, and get the property.

// lets say you're in a onchange client script
function(...){
  var mrvs = g_form.getValue('mrvs');
  // parse the raw data
  var parsedMrvs = JSON.parse(mrvs);
  // now you can access its rows, and since its a mrvs there's multple
  // to loop over;
  var rows = parsedMrvs.length;
  for(var x=0;x<rows;x++){
    console.log(parsedMrvs[x].order);//will output order
  }
}

John Shores1
ServiceNow Employee
ServiceNow Employee

Thank you! Worked like a champ.