Ankur Bawiskar
Tera Patron

Many a times there is a need to show dynamic choices in workspace form pane choice type field along with other fields.

Supported fields in Workspace form panes

There are different field types such as String, Date, Date/Time, Email etc.

One of those type is Choice where I will be adding the choices dynamically using GlideAjax.

Here is a sample UI action script which would fetch the choices from Change Request table and close_code field. I am also showing the Assignment Group field value on form pane.

You can refer this and enhance as per your requirement.

The key here is forming the JSON object containing the choice value and choice label.

UI Action:

Workspace Client Script:

function onClick(g_form) {

	var fields = [];
	fields.push({
		type: 'string',
		label: getMessage('Assignment Group'),
		value: g_form.getDisplayValue('assignment_group'),
		readonly: true,
	});

	var ga = new GlideAjax('GetMyChoices');
	ga.addParam('sysparm_name', 'getFieldChoices');
	ga.getXMLAnswer(function(answer1){
		var answer = JSON.parse(answer1);
		fields.push({
			type: 'choice',
			name: 'close_code',
			label: getMessage('Close code'),
			choices: answer.choices,
			mandatory: true
		});

		g_modal.showFields({
			title: "Choices for Change Request",
			fields: fields,
			size: 'lg'
		}).then(function(fieldValues) {

		});					

	});
}

UI action Configuration:

find_real_file.png

Script Include: Client callable

var GetMyChoices = Class.create();
GetMyChoices.prototype = Object.extendsObject(AbstractAjaxProcessor, {

	getFieldChoices: function(){

		var arr = [];
		// use this to add None if you wish to show when choices you are adding doesn't have it
		/*arr.push({
			"value":"",
			"displayValue":"-- None --"
		});
		*/

		// you can even iterate sys_choice and get the choice labels and values
		var choices = GlideChoiceList.getChoiceList("change_request", "close_code");
		for (var i = 0; i < choices.getSize(); i++){
			var value = choices.getChoice(i).getValue();
			var label = choices.getChoice(i).getLabel();
			var obj = {};
			obj["value"] = value.toString();
			obj["displayValue"] = label.toString();
			arr.push(obj);
		}
		var result = {};
		result["choices"] = arr;
		return JSON.stringify(result);
	},

	type: 'GetMyChoices'
});

Output: It is showing choices from close_code field of Change Request

find_real_file.png

Thanks for reading the blog and do provide your inputs/suggestions if any.

Hope you find this article helpful. Don’t forget to Mark it Helpful, Bookmark.
Thanks,
Ankur Bawiskar

ServiceNow MVP 2022,2021,2020,2019,2018

Developer MVP 2021

My Articles & Blogs

 

10 Comments
F_lix Dion
Kilo Expert

This is amazing! I've been looking forever for this solution, you are the real MVP!

Just a question: I've got close_code choices with labels in multiple languages and it seems to show the choices in english, how I can show them in a different language?

Thank you for your contribution to this community!

Monika Bhoyate1
Tera Contributor

Hi Ankur,

Thank you for wonderful article. I have a requirement to fetch string(multiple rows) data stored in custom table and show it as a choice in workspace popup window.

Is there any way we can do it?

Regards,

Monika

devservicenow k
Tera Contributor

How to Create Task in this pop up . suggest me. i need to create an task with after the choice fields

nileshwahul
Kilo Sage

Hi @Ankur Bawiskar , 

Indeed this is very helpful, Just by thinking one level up Can we have the choices also as dynamic as  assignment group.  

 

e.g. There are two fields, as in your example but instead of Close Code there is a field as assigned to which will be dependent on assignment group. So when I am selecting Assignment group as ABC , only ABC group members should be available to select in assigned to field.

Can we achieve this? Can we pass dynamically values to script Include each time we are changing assignment group? 

Please guide on this. Thanks !!!

Guneet Kaur
Tera Contributor

@Ankur Bawiskar Is it possible to add date field type?

harishkolla
Tera Contributor

@nileshwahul  Did you get any solution for the below ask,

 

e.g. There are two fields, as in your example but instead of Close Code there is a field as assigned to which will be dependent on assignment group. So when I am selecting Assignment group as ABC , only ABC group members should be available to select in assigned to field.

Can we achieve this? Can we pass dynamically values to script Include each time we are changing assignment group? 

Please guide on this. Thanks !

harishkolla
Tera Contributor

Hi @Ankur Bawiskar  Can you please help with below ask

 

There are two fields, as in your example but instead of Close Code there is a field as assigned to which will be dependent on assignment group. So when I am selecting Assignment group as ABC , only ABC group members should be available to select in assigned to field.

Can we achieve this? Can we pass dynamically values to script Include each time we are changing assignment group? 

Thank you

Mihir Patel
Tera Expert

@Ankur Bawiskar  or @harishkolla 

 

Did you find any solution for this?

 

I am in similar need where I am displaying users from sys_user reference inside of g_modal but I need to display specific group for the selected user from previous field. The groups belong to sys_user_group table. I tried GlideAjax call to my script include and it is returning a result. I tried pushing sys_id to string for reference qualifier and also tried pushing it to array as well, but nothing works inside of g_modal.

 

This has been working fine on the form itself of the workspace when I use reference qualifier but for some reason it does not work in g_modal.  So for example, if I select "Assigned To" field then the "Assignment Group" field shows only the groups for the selected user based on the reference qualifier on the form in workspace. But when I update the "assigned_to" using g_modal, set the value on the form (without saving), the second field on the g_modal does not display the appropriate group. 

dharmesh rathod
Tera Contributor

Hello @Ankur Bawiskar 

I have a similar requirement where I have to open a modal which will showcase CI's which are assigned to the caller. 

 

There is two major concerns which I'm facing - 
1. When I'm returning back result from Script include to Client script the array is not passing all objects(For Example if there are 2 CI's assigned to that caller only 2nd CI's Sys_id and Name is getting pushed into the array)

Script Include: 

var GetMyChoices = Class.create();
GetMyChoices.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    getFieldChoices: function() {
        var arr = [];
        var retData = [];
        var userId = this.getParameter('callerid');
        var choices = new GlideRecord('cmdb_ci');
        choices.addQuery('assigned_to', userId);
        choices.query();
        //var row = choices.getRowCount();
        while (choices.next()) {

            retData.push(choices.sys_id);

        }
        for (var i = 0; i <= retData.length; i++) {
            var value = choices.getValue('sys_id');
            var label = choices.getDisplayValue('name');
            var obj = {};
            obj["value"] = value.toString();
            obj["label"] = label.toString();
            arr.push(obj);
        }
        var result = {};
        result["choices"] = arr.toString();
        return JSON.stringify(arr);

    },

    type: 'GetMyChoices'

});

Refer the screenshot below:

dharmeshrathod_2-1707895649850.png

 

 

 

2. When I'm trying to push the array into the choice at that time the popup modal is not able to show any choices(It should showcase the CI names as choices and on selection of the choice the CI should get mapped in the CI field)

 

Client Script:

function onClick() {
    var fields = [];
    alert("111111111");
    var user = g_form.getValue('caller_id');
    alert("22222 :" +user );
    alert("Value of user : " + g_form.getValue('caller_id'));
    var ga = new GlideAjax('GetMyChoices');
   
    ga.addParam('sysparm_name', 'getFieldChoices');
    ga.addParam('callerid', user);
    alert("33333");
    ga.getXMLAnswer(function(answer1) {
        alert("44444 : " + answer1);
        var answer = JSON.stringify(answer1);
        alert("DRRRRR : " + answer);
        fields.push({
            type: 'choice',
            name: 'config_item',
            label: getMessage('Select CI'),
            choices: answer.label,
            mandatory: true
        });
        alert("555555");
        g_modal.showFields({
            title: "Choices for Change Request",
            fields: fields,
            size: 'lg'

        }).then(function(fieldValues) {

        });

    });

}

Refer Screenshot below:

dharmeshrathod_1-1707895585012.png

 

Ashutosh44
Tera Contributor

Hi @Ankur Bawiskar 

Why have you kept the showField logic inside Callback function of GlideAjax? I had a use case when Close code is selected as Duplicate, a reference field should be displayed in modal.
Since there is no way to mention hide/show logic here, I used a workaround to fulfill requirement and tried to show two modals
Can you please help me, my code is not working:

function onClick(g_form) {

    var choiceFields = [];
    var referenceFields = [];
    referenceFields.push({
            type: 'reference',
            name: 'parent',
            label: getMessage('Duplicate of'),
            reference: 'sn_gsm_enquiry',
            referringTable: 'sn_gsm_enquiry',
            referringRecordId: g_form.getUniqueValue(),
        });
       
    var ga = new GlideAjax('GetResolutionCodes');
    ga.addParam('sysparm_name', 'getFieldChoices');
    ga.getXMLAnswer(function(answer1) {
        var answer = JSON.parse(answer1);
        choiceFields.push({
            type: 'choice',
            name: 'resolution_code',
            label: getMessage('Resolution code'),
            choices: answer.choices,
            mandatory: true
        });

        g_modal.showFields({
            title: "Enter your reason",
            fields: choiceFields,
            size: 'lg'
        }).then(function(selectedCode) {
            // if Duplicate is selected
            if (selectedCode.updatedFields[0].value == '4') {
                g_modal.showFields({
                    title: 'Enter Duplicate Enquiry number',
                    fields: referenceFields,
                    size: 'lg',
                    //height: 'md'
                }).then(function(selectedEnq) {
                    g_form.setValue('resolution_code', selectedCode.updatedFields[0].value);
                    var duplicateEnq = selectedEnq.updatedFields[0].value;
                    if (duplicateEnq != '') {
                        g_form.setValue('parent', duplicateEnq);
                    }
                    g_form.setValue('state', '7');
                    g_form.save();

                });

            } else {
                g_form.setValue('resolution_code', selectedCode.updatedFields[0].value);
                g_form.setValue('state', '7');
                g_form.save();
            }
        });
    });
}