logo

NJP

CartJS: How to populate a MRVS (Multi Row Variable Set)

Import · Feb 12, 2022 · article

How to set a MRVS (Multi Row Variable Set) for CartJS API

Intro: A Multi RowVariable Set (MRVS) can be set in a server or background script with proper syntax formatting. The MRVS is a JSON object that has been passed through JSON.stringify() and is surrounded with square brackets "[" and "]". The basic steps to get the data formatted correctly is to:

  1. Create a JSON object with properties and values of a MRVS
  2. JSON.stringify() the JSON object
  3. Add square brackets [ ] to the start and end of the string.

Shown below are two examples of how to create the data along with a function that will convert a JSON object to a string in the proper MRVS syntax.

Example 1 :

Create a JSON object

var mrvsData = {
    variableString1 : "string",
    booleanValue1 : true
};

Perform a JOSN.stringify(mrvsData) on the data to get:

'{"variableString1":"string","booleanValue1":true}'

Now surround the string with [ ]

'[{"variableString1":"string","booleanValue1":true}]'

This data can now be used to set a variable in the CartJS API

Example 2:

Here is a full code example of a catalog item that has a MRVS utilizing the CartJS API

var cart = new sn_sc.CartJS();
var item = {
    'sysparm_id': 'a9cad13a2f110110c9ebdcb6f699b6fa',
    'sysparm_quantity': '1',
    'variables': {
        'string_on_base_vars': 'Sample String Value',
        'mrvs_demo': '[{"mrvs_date_var":"2022-02-04","mrvs_checkbox_var":"true"}]'
    }
};
var cartDetails = cart.addToCart(item);
var checkoutInfo = cart.checkoutCart();
gs.info(checkoutInfo);

Function to convert JSON values to MRVS data:

/*
  Converts a JSON value into MRVS (Multi-Row Variable Set) to be used by the Cart JS Api.
  @param{string|object} - JSON object or string value to be converted to MRVS (Multi Row Variable Set) string
  @return{string} String value to be used for a MRVS (Multi Row Variable Set)
*/
function convertJsonToMrvs(jsonValue){
    //Handle multiple input types
    if(typeof jsonValue === "string"){
        try{
            gs.debug("String received for f(x) convertJsonToMrvs")
            var objJson = JSON.parse(jsonValue);
            jsonValue = objJson;
        }catch(error){
            gs.error("Unable to convert: " + jsonValue + "  into a JSON object. Source, F(x) convertJsonToMrvs");
        }
    }else if (typeof jsonValue === "object"){
        gs.debug("JSON object recevied for f(x) convertJsonToMrvs");
    }else{
        gs.error("Improper object passed into F(x) convertJsonToMrvs");
    }

    //Perform conversion
    var strMrvsData = JSON.stringify(jsonValue);
    strMrvsData = "[" + strMrvsData + "]";
    gs.debug("Return Value for f(x) convertJsonToMrvs:   " + strMrvsData);
    return strMrvsData;
}
View original source

https://www.servicenow.com/community/now-platform-articles/cartjs-how-to-populate-a-mrvs-multi-row-variable-set/ta-p/2312078