Need to Print the FirstName and Last Name in Short Description

sayanghosh0
Tera Contributor

Hello Team,


I am trying to put the FirstName and LastName in Short Description when the Caller changes.
Script Include:

sayanghosh0_0-1737152526302.png

 


On Change Client Script:
sayanghosh0_1-1737152552965.png

 

Getting the Below Output:
sayanghosh0_0-1737152288240.png

 



Best Regards



1 ACCEPTED SOLUTION

Siddhesh Jadhav
Kilo Sage

Hi @sayanghosh0 ,

 

Suggested Solution:

Your current issue is caused by how you are handling the response from the Script Include. Since the Script Include returns an array (even if it contains just one object), you need to access the first index [0] of the array to retrieve the caller's information.

Here’s a step-by-step guide to resolve the issue:

 

  1. Update Your Client Script
    Modify the client script to properly handle the array returned from the Script Include:

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
	if (isLoading || newValue === '') {
		return;
	}

	var glideAjax = new GlideAjax('IncidentUtils');
	glideAjax.addParam('sysparm_name', 'callerInfo');
	glideAjax.addParam('sysparm_caller', newValue);
	glideAjax.getXMLAnswer(pop);

	function pop(response) {
		if (response) {
			var answer = JSON.parse(response);
			alert('answer' + answer);
			var sd = 'First Name : ' + answer[0].firstName + ' Last Name : ' + answer[0].lastName;
			g_form.setValue('short_description', sd);
		} else {
			alert('error');
		}
	}
}

 

  • Understanding the Script Include
    Since your Script Include is returning an array, even if it contains only one object, ensure the client script processes the array correctly.

  • Recommendation
    In my opinion, there is no need to return an array from the Script Include when you are dealing with just one object. Instead, you can directly return the object.

 

var IncidentUtils = Class.create();
IncidentUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    callerInfo: function () {
        var callerSysId = this.getParameter('sysparm_caller');
        var userRecord = new GlideRecord('sys_user');
        userRecord.addQuery('sys_id', callerSysId);
        userRecord.query();

        if (userRecord.next()) {
            var userObj = {
                firstName: userRecord.first_name.toString(),
                lastName: userRecord.last_name.toString()
            };
            return JSON.stringify(userObj); // Return an object instead of an array
        }
        return null;
    },
    type: 'IncidentUtils'
});

 

 

If this answer helps you solve your query, please mark it as accepted and helpful.

 

Best Regards,
Siddhesh Jadhav

View solution in original post

7 REPLIES 7

TejaswiniY
Tera Contributor

Hello @sayanghosh0 

Here’s a sample code snippet in ServiceNow to automatically update the Short Description of an Incident with caller first name and last name, whenever the Caller field is changed. 

=================================================================================

Script Include:

***********************

Code:

var ScriptIncludeForCallerDetails = Class.create();
ScriptIncludeForCallerDetails.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    getData: function() {
        var user = this.getParameter('sysparm_user');
        var obj = {};
        var usr = new GlideRecord('sys_user');
        usr.addQuery('sys_id', user);
        usr.query();
        if (usr.next()) {
            obj.firstName = usr.first_name.getDisplayValue();
            obj.lastName = usr.last_name.getDisplayValue();
          }
        return JSON.stringify(obj);
    },
    type: 'ScriptIncludeForCallerDetails'
});
 ==============================================================================
On change client script:
******************************
table: Incident
UI type: All
Type: onchange
field: caller
Code:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    var ga1 = new GlideAjax('ScriptIncludeForCallerDetails');
    ga1.addParam('sysparm_name', 'getData');
    ga1.addParam('sysparm_user', newValue);
    ga1.getXMLAnswer(setDetails);
    function setDetails(response) {
        var pVal = JSON.parse(response);
        var details = "FIRST NAME : " + pVal.firstName + " " + "LAST NAME : " + pVal.lastName;
        g_form.setValue('short_description', details);
    }
}
 

If this addresses your question, please mark this response as Accepted Solution or mark has Helpful if you find it helpful.

Thank you!

TejaswiniY

TejaswiniY
Tera Contributor

Hello @sayanghosh0 

Here’s a sample code snippet in ServiceNow to automatically update the Short Description of an Incident with caller's first name and last name, whenever the Caller field is changed. 

======================================================================================

Script Include:

*********************************

Code:

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

    getData: function() {
        var user = this.getParameter('sysparm_user');
        var obj = {};
        var usr = new GlideRecord('sys_user');
        usr.addQuery('sys_id', user);
        usr.query();
        if (usr.next()) {
            obj.firstName = usr.first_name.getDisplayValue();
            obj.lastName = usr.last_name.getDisplayValue();
        }
        return JSON.stringify(obj);
    },
    type: 'ScriptIncludeForCallerDetails'
});
 =========================================================================
Client script:
Table: Incident
Ui type: All
Type : Onchange
field : caller
 *******************************************
Code:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    var ga1 = new GlideAjax('ScriptIncludeForCallerDetails');
    ga1.addParam('sysparm_name', 'getData');
    ga1.addParam('sysparm_user', newValue);
    ga1.getXMLAnswer(setDetails);

    function setDetails(response) {
        var pVal = JSON.parse(response);
        var details = "FIRST NAME : " + pVal.firstName + " " + "LAST NAME : " + pVal.lastName;
        g_form.setValue('short_description', details);
    }
}

If this addresses your question, please mark this response as Accepted Solution ✔️ or mark has helpful 👍 if you find it helpful.

Thank you!

TejaswiniY

 

Brad Bowman
Kilo Patron
Kilo Patron

Make sure your Script Include is Client callable.  If you check this box after the script is populated, it may not add what it needs to.  Your Script Include should look more like this::

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

    auto1: function() {
        ....
    },

    type: 'Auto_Populate'
});

This may not matter, but you should also end the onChange function before initializing the pop function, so move the end bracket to after the getXMLAnswer line.

 

If it's still not working, make sure the Script Include is in the same scope/application as the Client Script, and that the user has the role listed in the Access Control related list, if there is one.  You can add some gs.addInfoMessage lines to the Script Include to confirm that it is running, the value of the parameter, etc., and alert on response and obj in the Client Script to see if you are parsing that correctly.  In this simplified example, you don't need an array in the Script Include or the Client Script as only one object will be returned.

AakashG1819
Tera Contributor

Hlo @sayanghosh0,

Hope you are doing well.

 

Proposed Solution

In order to achieve this task and to give you an appropriate solution of this problem, I personally tried and implemented it on my Personal Developer Instance so that you can get an appropriate solution as soon as possible. For this, as you already know you need to create "1 On-Change Client Script" and "1 Script Include" and then link them with the help of Glide Ajax to get the First and Last Name of a Caller and set the values in Short Description with an appropriate message. Let me give you my Scripts that I wrote for you and it seems to be working fine for me and I believe that it'll work for you as well.

 

On-Change Client Script

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    var callerAjax = new GlideAjax('global.Update_Short_Description');
    callerAjax.addParam('sysparm_name', 'getFirstAndLastName');
    callerAjax.addParam('sysparm_caller', newValue);
    callerAjax.getXML(result);

    function result(response) {
        var answer = response.responseXML.documentElement.getAttribute("answer");
        var ans = JSON.parse(answer);
        g_form.addInfoMessage(ans[0].first_name + " " + ans[0].last_name);
        var str = "First Name is " + ans[0].first_name + ", and Last Name is " + ans[0].last_name + ".";
        g_form.setValue('short_description', str);
    }

}

 

Script Include

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

    getFirstAndLastName: function() {
        var caller = this.getParameter('sysparm_caller');
        var grUser = new GlideRecord("sys_user");
        grUser.addQuery("sys_id", caller);
        grUser.query();
        if (grUser.next()) {
            var arr = [];
            var obj = {
            "first_name" : grUser.first_name.toString(),
            "last_name" : grUser.last_name.toString()
			};
            arr.push(obj);
        }
        return JSON.stringify(arr);

    },
    type: 'Update_Short_Description'
});

 

For your reference and just to show you the results, also attaching snapshots of the outputs that will give you better insights of how the script is working or the best thing will be to follow the solution and execute the scripts on your instance.

Before Change Caller Field

AakashG1819_0-1737295097223.png


After Change Caller Field

AakashG1819_1-1737295337162.png

 

If you find this information/knowledge/solution helpful, please don't forget to mark my solution as helpful and Accepted as a Solution.

Thanks 🙂

Aakash Garg

ServiceNow Developer