How to fetch the values and update on another field for the same form.

AnnamalaiS76596
Mega Contributor

Current State:
In the new form creation, under the Access to Existing Folder option:
Select Volume (multiple choice) currently has only one value.
Select Folder (multiple choice) currently has only two values.
New Requirement:
After task completion—once the folder name and volume name are created in their system—we need to store the values entered by the user in the request (i.e., folder name or volume name (multiline text) [selected under Create New Folder or Create New Volume)].
These stored values should then be fetched dynamically and displayed in the Select Folder and Select Volume fields.
Please guide me to write workflow script. At present, there is no option to store these values in a custom table.

7 REPLIES 7

Ankur Bawiskar
Tera Patron
Tera Patron

@AnnamalaiS76596 

share some screenshots without which we can't help

is this for catalog item?

what did you start with in scripting and where are you stuck?

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

rafaelramos0
Tera Expert

Hi @AnnamalaiS76596 !

I'm not sure I understand, but this would require some script or flow.

I've never done this, but I think you could try creating a choice record based on the values ​​entered in the "new value" fields.

Steps:
1 - Obtain the value related to "New Field".
2 - Check if the selection option already exists for the specific element and table.
3 - If it does not exist, create the record for the selection option for the specific element and table with the informed value.

I see some potential problems:
#1 - Field length defined for "new values".
#2 - Number of option records that can be created for the same element.

#3 - Possible platform restriction that prevents this action.

Mark helpful if makes sense.  🙂

AnnamalaiS76596
Mega Contributor

Yes, it is catalog item.
I tried 2 program which not working.

1. 

(function execute(inputs, outputs) {
    var ritm = current.request_item;
    if (!ritm) {
        ritm = new GlideRecord('sc_req_item');
        ritm.get(current.request_item.sys_id);
    }
    function getVariableValues(variableName) {
        var gr = new GlideRecord('sc_item_option');
        gr.addQuery('request_item', ritm.sys_id);
        gr.addQuery('item_option_new.name', variableName);
        gr.query();

        var values = [];
        while (gr.next()) {
            values.push(gr.value.toString());
        }
        return values;
    }
    var folderValues = getVariableValues('folder_name');
    var volumeValues = getVariableValues('volume_name');
    var ritmGR = new GlideRecord('sc_req_item');
    if (ritmGR.get(ritm.sys_id)) {
        var folderVar = new global.GlideElementFactory().getElement('select_folder_name', ritmGR.variables);
        if (folderVar) {
            folderVar.setChoices(folderValues);
        }
        var volumeVar = new global.GlideElementFactory().getElement('select_volume', ritmGR.variables);
        if (volumeVar) {
            volumeVar.setChoices(volumeValues);
        }
    }
})(inputs, outputs);


2.

var newFolder = current.variables.folder_name;
var newVolume = current.variables.volume_name;
if (newFolder && newFolder != '') {
    var folderQuestionId = getQuestionSysId('select_folder_name');
    addQuestionChoice(folderQuestionId, newFolder, newFolder);
}
if (newVolume && newVolume != '') {
    var volumeQuestionId = getQuestionSysId('select_volume');
    addQuestionChoice(volumeQuestionId, newVolume, newVolume);
}
function getQuestionSysId(varName) {
    var gr = new GlideRecord('item_option_new');
    gr.addQuery('name', varName);
    gr.addActiveQuery();
    gr.query();
    if (gr.next()) {
        return gr.question.toString();
    }
    gs.warn('Variable "' + varName + '" not found in item_option_new');
    return null;
}
function addQuestionChoice(questionId, value, text) {
    if (!questionId) return;
    var grChoice = new GlideRecord('question_choice');
    grChoice.addQuery('question', questionId);
    grChoice.addQuery('value', value);
    grChoice.query();
    if (!grChoice.next()) {
        grChoice.initialize();
        grChoice.question = questionId;
        grChoice.text = text;
        grChoice.value = value;
        grChoice.order = 100;
        grChoice.inactive = false;
        var sysId = grChoice.insert();
        gs.info('Added question_choice: ' + text + ' (sys_id: ' + sysId + ')');
    } else {
        gs.info('Question choice already exists: ' + value);
    }
}

AnnamalaiS76596
Mega Contributor

even though I tried on load client script

function onLoad() {
    setTimeout(function() {
        var ritmSysId = g_form.getUniqueValue();
        if (!ritmSysId) {
            console.warn("onLoad: ritmSysId is empty");
            return;
        }
        var ga = new GlideAjax('FetchRITMVariables');
        ga.addParam('sysparm_name', 'getVariables');
        ga.addParam('sysparm_ritmSysId', ritmSysId);
        ga.getXMLAnswer(function(response) {
            if (!response) {
                console.error("GlideAjax returned empty response");
                return;
            }
            try {
                var data = JSON.parse(response);
                console.log("Fetched variables:", data);
                if (data && data['folder_name'] && Array.isArray(data['folder_name'])) {
                    g_form.clearOptions('select_folder_name');
                    data['folder_name'].forEach(function(opt) {
                        if (opt) {
                            g_form.addOption('select_folder_name', opt, opt);
                        }
                    });
                }
                if (data && data['volume_name'] && Array.isArray(data['volume_name'])) {
                    g_form.clearOptions('select_volume');
                    data['volume_name'].forEach(function(opt) {
                        if (opt) {
                            g_form.addOption('select_volume', opt, opt);
                        }
                    });
                }
            } catch (e) {
                console.error("Error parsing or processing response:", e, response);
            }
        });
    }, 200);
}

script include client callable.

var FetchRITMVariables = Class.create();
FetchRITMVariables.prototype = {
    initialize: function() {},
    getVariables: function(ritmSysId) {
        var result = {};
        var gr = new GlideRecord('sc_item_option');
        gr.addQuery('request_item', ritmSysId);
        var qc1 = gr.addQuery('item_option_new', '32bf83f33ba936100e250344c3e85ae9');
        qc1.addCondition('value', '!=', '');
        var qc2 = gr.addQuery('item_option_new', '4f8204103339b210befddef6ee5cyb15');
        qc2.addCondition('value', '!=', '');

        gr.addOrCondition(qc1);
        gr.addOrCondition(qc2);
        gr.query();

        while (gr.next()) {
            var name = gr.getValue('item_option_new.name');
            if (!name) {
                name = gr.getValue('name');
            }
            var value = gr.getValue('value');
            if (!result[name]) {
                result[name] = [];
            }
            result[name].push(value);
        }

        return JSON.stringify(result);
    },

    type: 'FetchRITMVariables'
};