The CreatorCon Call for Content is officially open! Get started here.

Showing MRVS on SC_Task

tanvipalkar
Tera Contributor

Hello Community,

I am trying to display MRVS present on catalog item to sc_task genenrated after approving the RITM.

I am using client script and script include, but not able to show MRVS on sc_task.

Only problem is HTML table is not appearing on sc_task by using jQuery or setValue() using the HTML field. 

MRVS is appearing on info message when I am using gs.info() to get table.

Please provide insights on how to solve this problem.Help would be greatly appreciated.

Thank you!

Find attached SScreenshot of gs.info() displaying MRVS:

tanvipalkar_0-1758912928353.png

 

 

Please find below client script and script include:

Note : script include is Client callable and Client script is on sc_task (Onload) and  isolated is unckecked 

Script include:

var multiRowVariablesSet = Class.create();
multiRowVariablesSet.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
    getQA: function() {
        //Returns a JSON object representing all the MRVS for a particular requested item along with their values
        var sys_id = this.getParameter('sysparm_sys_id') || '2a175e5edb830090b3da126b3a9619b1';
        var allMRVS = [];
        var ritm = new GlideRecord('sc_req_item');
        gs.info('11');
        if (ritm.get(sys_id)) {
            gs.info('22');
            //loop through the variables looking for multi-row variable sets
            for (var eachVar in ritm.variables) {

                gs.info('33'+eachVar);
                //found one!
                if (ritm.variables[eachVar].isMultiRow()) {
                    gs.info('44');
                    //////////////////////////////////////////
                    //get Multi-Row Variable Set structure
                    var mrvsDefintion = {},
                        title = '';
                    var mrvsStructure = new GlideRecord('item_option_new');
                    //internal_name added
                    gs.info('55');
                    //mrvsStructure.addEncodedQuery('active=true^variable_setISNOTEMPTY^variable_set.multi_row_variable=' + eachVar);
mrvsStructure.addEncodedQuery('active=true^variable_setISNOTEMPTY^variable_set.internal_name=multi_row_variable');
                    gs.info('66');
                    mrvsStructure.orderBy('order');
                    gs.info('77');
                    mrvsStructure.query();
                    gs.info('88'+mrvsStructure.getRowCount());

                    while (mrvsStructure.next()) {
                        gs.info('w1');
                        //What is the title of this MRVS?
                        if (title == '') title = mrvsStructure.variable_set.title.toString();
                        gs.info('w1');
                        //What about each of the variables
                        mrvsDefintion[mrvsStructure.name.toString()] = {
                            "name": mrvsStructure.name.toString(),
                            "question": mrvsStructure.question_text.toString(),
                            "sys_id": mrvsStructure.sys_id.toString(),
                            "type": mrvsStructure.type.getDisplayValue(),
                            "table": mrvsStructure.type.getDisplayValue() == "Reference" ? mrvsStructure.reference.getValue() : "",
                            "order": mrvsStructure.order.toString(),
                            "row""",
                            "value"""
                        };
                        gs.info('w2');
                    }
                    //////////////////////////////////////////
                    //get the Multi-Row Variable Set values
                    var mrvsValue = [];
                    var mrvsAnswers = new GlideRecord('sc_multi_row_question_answer');
                    gs.info('w3');
                    //mrvsAnswers.addEncodedQuery('parent_id=' + sys_id + '^variable_set.multi_row_variable=' + eachVar);      mrvsAnswers.addEncodedQuery('variable_set=03aed7ce3388fa10f62ad3382e5c7b65^parent_id=6a9f534233c8fa10f62ad3382e5c7b8a');
                    gs.info('w4');
                    mrvsAnswers.orderBy('row_index');
                    gs.info('w5');
                    mrvsAnswers.query();
                    gs.info('w6'+mrvsAnswers.getRowCount());
                    while (mrvsAnswers.next()) {
                        gs.info('w7');
                        var thisVariable = mrvsAnswers.item_option_new.name.toString();
                        gs.info('w8');
                        if (mrvsDefintion.hasOwnProperty(thisVariable)) {
                            //Get value
                            gs.info('w9');
                            var thisValue = mrvsAnswers.value.toString();
                            gs.info('w10');
                            //if this is a reference field get the display value
                            if (mrvsDefintion[thisVariable].type == 'Reference' && mrvsDefintion[thisVariable].table != '') {
                                gs.info('w11');
                                var getDisplayVal = new GlideRecord(mrvsDefintion[thisVariable].table);
                                gs.info('w12');
                                if (getDisplayVal.get(thisValue)) {
                                    gs.info('w13');
                                    thisValue = getDisplayVal.getDisplayValue();
                                }
                                gs.info('w14');
                            }
                            //If this is a select box with choices, get the question_choice (display value)
                            gs.info('w15');
                            if (mrvsDefintion[thisVariable].type == 'Select Box') {
                                gs.info('w16');
                                var getQuestionChoice = new GlideRecord('question_choice');
                                getQuestionChoice.addEncodedQuery('question=' + mrvsDefintion[thisVariable].sys_id + '^value=' + thisValue);
                                gs.info('w17');
                                getQuestionChoice.query();
                                gs.info('w18');
                                if (getQuestionChoice.next()) {
                                    gs.info('w19');
                                    thisValue = getQuestionChoice.text.toString();
                                }
                            }
                            gs.info('w20');
                            mrvsDefintion[thisVariable].value = thisValue;
                            mrvsDefintion[thisVariable].row = mrvsAnswers.row_index.toString();
                            mrvsValue.push(JSON.parse(JSON.stringify(mrvsDefintion[thisVariable]))); //push in a clean object
                        }
                    }
                    allMRVS.push({
                        "name": title,
                        "details": mrvsValue
                    });
                }
            }
        }
        gs.info('return' + JSON.stringify(allMRVS));
        return JSON.stringify(allMRVS);
    },
    type: 'multiRowVariablesSet'
});
 
client script :
function onLoad() {
    if(g_form.getValue('request_item')!=''){
        //Check for a multi-row variable set
        var gaMRVS = new GlideAjax('multiRowVariablesSet');
        gaMRVS.addParam('sysparm_name','getQA');
        gaMRVS.addParam('sysparm_sys_id',g_form.getValue('request_item'));
        gaMRVS.getXMLAnswer(displayResults);
    }
    ///////////////////////////////////////////////////////
    function displayResults(results){
        var allMRVS = JSON.parse(results), htmlTable = '';
        // var allMRVS = JSON.stringify(results), htmlTable = '';
        // alert("f2"+ JSON.stringify(allMRVS));

        allMRVS.forEach(function(mvrs){
            if(mvrs.details.length !=0){
                //First, sort results by row then by order
                mvrs.details.sort(function(a, b) {if (a.row === b.row) {return a.order > b.order ? 1 : -1;} return a.row > b.row ? 1 : -1;});
                //We'll add our MRVS as a table beneath the description field
                htmlTable+= '<div class="form-group"><div><label class="col-xs-12 col-md-1_5 col-lg-2 control-label"><span aria-label="" data-dynamic-title="" mandatory="false" oclass="" class=" "></span><span title="" class="label-text" data-html="false" data-original-title="" aria-expanded="false">'+mvrs.name+'</span></label></div><div class="col-xs-10 col-md-9 col-lg-8 form-field input_controls"><table style="border-collapse: collapse;border-right:1px solid silver;border-bottom:1px solid silver;width:100%"><tr>';
                //Get the first row number
                var rowNumber = mvrs.details[0].row;
                //get column headers
                mvrs.details.forEach(function(thisEntry){
                    if(thisEntry.row == rowNumber){
                        htmlTable+= '<td style="padding:10px !important;border-left:1px solid silver;border-top:1px solid silver;background-color:WhiteSmoke;">'+thisEntry.question+'</td>';
                    }
                });
                rowNumber = '';
                //add each row
                mvrs.details.forEach(function(thisEntry){
                    //insert a new row each time the row number changes
                    if(thisEntry.row != rowNumber) htmlTable+= '</tr><tr>';
                    //add each individual cell value (knowing it has been sorted correctly so they'll all be in order)
                    htmlTable+= '<td style="padding:10px !important;border-left:1px solid silver;border-top:1px solid silver;">'+thisEntry.value+'</td>';
                    rowNumber = thisEntry.row;                  
                });

                htmlTable+= '</tr></table></div>';
            }
        });
        g_form.addInfoMessage(htmlTable);
        jQuery('#element\\.sc_task\\.project_type').after(htmlTable);
        //g_form.setValue('multi_row_task',htmlTable); //multi_row_task is HTML field
    }
}
 
 
4 REPLIES 4

Rafael Batistot
Kilo Patron

Hi @tanvipalkar 

 

On the server side (Script Include), your logic correctly queries the MRVS and builds a JSON object.

 

On the client side, you are building the HTML table and trying to inject it into the form (addInfoMessage, jQuery().after(), or setValue() into an HTML field).

 

The problem is:

  • jQuery selectors (#element\\.sc_task\\.project_type) do not always work in the scoped UI of ServiceNow — especially in newer UI (UI16, Workspace).
  • HTML fields in forms sanitize or strip injected HTML when using g_form.setValue(). That’s why your table does not render.
  • addInfoMessage() works because that API accepts raw HTML.

 

If you found this response helpful, please mark it as Helpful. If it fully answered your question, consider marking it as Correct. Doing so helps other users find accurate and useful information more easily.

Hello @Rafael Batistot 

Thanks for reply.

How to resolve this problem?

Is there any solution to build html table on sc_task variable section?

Thank you!

Hi @tanvipalkar 

 

May your try use a “Display” field (String/HTML) on sc_task

 

  • Create a new field on sc_task (e.g. u_mrvs_display).
  • Populate it with formatted MRVS values when the task is created:
    • Use a Business Rule on sc_task after insert (or on the RITM → Task creation logic).
    • Server-side, query sc_multi_row_question_answer for the RITM’s MRVS answers.
    • Build an HTML table string.
    • Set current.u_mrvs_display = htmlString.
  • On the form, configure the field to display as HTML type, so the table renders properly.

This avoids client-side injection issues and keeps the MRVS snapshot stored with the task.

 

2. Use addInfoMessage() onLoad (quick & dirty)

 

  • You already saw this works.
  • You can keep using g_form.addInfoMessage(htmlTable) in the onLoad client script.
  • Downside: it won’t be stored in the record, and it disappears if the form reloads without the script.

Use a “Display” field (String/HTML) on sc_task

  • Create a new field on sc_task (e.g. u_mrvs_display).
  • Populate it with formatted MRVS values when the task is created:
    • Use a Business Rule on sc_task after insert (or on the RITM → Task creation logic).
    • Server-side, query sc_multi_row_question_answer for the RITM’s MRVS answers.
    • Build an HTML table string.
    • Set current.u_mrvs_display = htmlString.
  • On the form, configure the field to display as HTML type, so the table renders properly.

This avoids client-side injection issues and keeps the MRVS snapshot stored with the task.

If you found this response helpful, please mark it as Helpful. If it fully answered your question, consider marking it as Correct. Doing so helps other users find accurate and useful information more easily.

Brad Bowman
Kilo Patron
Kilo Patron

Why on earth would you go through all of this in an attempt to replicate out of box functionality?  If you want to display a MRVS on a Catalog Task, add it to the Catalog Task activity in Workflow Editor or Flow Designer.