Check if username exists, and if so then increment by one number at the user name end

vikas50
Tera Contributor

I want to check if a user name exists in the user table and the user name should be a combination of first and last names. If it exists then add a number to the end of the last name starting from +1

Example: "Mark Henry" already exists try ''Mark Henry1'' if ''Mark Henry1'' exists then create "Mark Henry 2"

1 ACCEPTED SOLUTION

Amit Pandey
Kilo Sage

Hi @vikas50 

 

Would encourage you to create before/insert business rule on sys_user table with following script-

 

(function executeRule(current, previous /*null when async*/ ) {
    if (current.isNewRecord()) {
        var firstName = current.first_name;
        var lastName = current.last_name;
        var userName = firstName + ' ' + lastName;

        var userGr = new GlideRecord('sys_user');
        userGr.addQuery('user_name', userName);
        userGr.query();
        
        if (userGr.next()) {
            var newName = userName;
            var count = 1;
            do {
                newName = userName + count;
                userGr.initialize();
                userGr.addQuery('user_name', newName);
                userGr.query();
                count++;
            } while (userGr.next());
            current.user_name = newName;
        } else {
            current.user_name = userName;
        }
    }
})(current, previous);

Regards,

Amit

View solution in original post

14 REPLIES 14

AakashGarg1678
Kilo Guru

Hi @vikas50,
Hope you are doing well.

 

I got your requirement clearly as you want to automatically increase the count by 1 if user is already exists in user table and tried to implement the same on my PDI and coming up with the solution along with the scripts and snapshots that will really gonna help you and other to get the solution with the help of your question asked in the community.

 

Proposed Solution

As a solution, you need to create a "Before-Insert/Update Business Rule" that will execute the logic or implementation as per the new record inserted or old record updated in user table. Attaching the script that will work for you.

 

(function executeRule(current, previous /*null when async*/) {

	var first_name = current.first_name;
	var last_name = current.last_name;
	var name = first_name + ' ' + last_name;
	var user_name = first_name + '.' + last_name;
	var count = 0;
	var gr = new GlideRecord('sys_user');
	gr.addQuery('name', 'STARTSWITH', name);
	gr.query();
	while(gr.next()){
		count+=1;
	}
	current.user_name = user_name + count;
	// current.name = name + count; Not working as expected

})(current, previous);

 

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

 

Note: - I tried to change the "Name" Field value by using the "current.name = user_name + count" as you can see a line in my script as a comment, but unable to do so. With this, I found that it may not be useful as any Business Rule is overwritten this task.

 

If you find this answer/solution/suggestion as helpful to your question asked or meet with your requirement, you can mark this solution/answer/suggestion as helpful, and correct.

 

Thanks

Aakash Garg

ServiceNow Developer

AakashGarg1678
Kilo Guru

Hi @vikas50,

Hope you are doing good.

 

I just got your requirement that you need the solution in the form of Client Script and Script Include only and tried to implement the same on my PDI and coming up with the solution along with the scripts and snapshots that will really gonna help you and other to get the solution with the help of your question asked in the community.

 

Proposed Solution

As a solution, you need to create an "On-Change Client Script" that will execute the logic or implementation as per the "Last Name" Field changes on the user form or record. Attaching the script that will work for you.

 

Client Script

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

    //Type appropriate comment here, and begin script below
	var first_name = g_form.getValue("first_name");	// Getting First Name
	var last_name = g_form.getValue("last_name");	// Getting Last Name
    var ga = new GlideAjax('global.CreateNewUserNameIfExists'); // GlideAjax Call
    ga.addParam('sysparm_name', 'getCampus'); // Calling Function
    ga.addParam('sysparm_first_name', first_name); // Passing User First Name
	ga.addParam('sysparm_last_name', last_name); // Passing User Last Name
    ga.getXML(updateCampus);

    function updateCampus(response) {
        var answer = response.responseXML.documentElement.getAttribute("answer"); // Getting Response
        if (answer) {
			g_form.setValue('user_name', first_name + '.' + last_name + parseInt(answer));
        }
    }

}

 

Script Include

var CreateNewUserNameIfExists = Class.create();
CreateNewUserNameIfExists.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    getCampus: function() {
		var first_name = this.getParameter('sysparm_first_name');
		var last_name = this.getParameter('sysparm_last_name');
		var name = first_name + ' ' + last_name;
        var count = 0;
        var gr = new GlideRecord('sys_user');
        gr.addQuery('name', 'STARTSWITH', name);
        gr.query();
        while (gr.next()) {
            count += 1;
        }
        return count;
    },
    type: 'CreateNewUserNameIfExists'
});

 

For your reference, also attaching screenshots of the outputs that will give you better insights of how this script is working and changing the username field automatically as soon as "last name" field gets changed or the best thing will be to follow the solution and execute the script on your instance.

 

If you find this answer/solution/suggestion as helpful to your question asked or meet with your requirement, you can mark this solution/answer/suggestion as helpful, and correct.

 

Thanks

Aakash Garg

ServiceNow Developer

Hi @AakashGarg1678 ,

I have configured a catalog form to perform validation using client script and script include. currently it is checking the user exists or not , if doesn't exist, it populates the user name combination of first name and last name but in my case I need the script should also check if a user with the same first name and last name combination already exists. If it does, the script should append a number to the end of the last name.

vikas50_2-1711106073934.pngvikas50_3-1711106087684.png

can you help me identify where I can add extra conditions to implement the mentioned functionality

Hi @vikas50,

Hope you are doing well and glad to see that you are following my solution. I'll make sure you get your query resolved as soon as possible.

 

To append a number to the end of the last name, I tried it on my PDI to get it resolved for you. It was quite hard to get the solution for this. But unfortunately, I succeeded.

 

As a solution, this part is an addition to my previous comment, you just need to modify the "On-Change Client Script" that will execute the logic or implementation as per the "Last Name" Field changes on the user form or record. Attaching the updated script that will work for you.

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    //Type appropriate comment here, and begin script below
    if (g_form.getValue('user_name') == '') {
        var first_name = g_form.getValue("first_name"); // Getting First Name
        var last_name = g_form.getValue("last_name"); // Getting Last Name
        var str = last_name.slice(0, -1);
        var ga = new GlideAjax('global.CreateNewUserNameIfExists'); // GlideAjax Call
        ga.addParam('sysparm_name', 'getCampus'); // Calling Function
        ga.addParam('sysparm_first_name', first_name); // Passing User First Name
        ga.addParam('sysparm_last_name', str); // Passing User Last Name
        ga.getXML(updateCampus);

        function updateCampus(response) {
            var answer = response.responseXML.documentElement.getAttribute("answer"); // Getting Response
            if (answer) {
                g_form.setValue('user_name', first_name + '.' + last_name + parseInt(answer));
                g_form.setValue('last_name', last_name + parseInt(answer));
            }
        }
    }
}

 

For your reference, also attaching screenshots of the outputs that will give you better insights of how this script is working and changing the "username" field as well as the "last name" field automatically or the best thing will be to follow the solution and execute the script on your instance.

 

Let me know if you find this helpful anyway, and please don't forget to mark my solutions and replies as helpful and accepted. 

 

Thanks 🙂

Aakash Garg

ServiceNow Developer 

Thanks Aakash!

It is not working for me , If the user doesn't exists it adds '0' at the end and if it exists it adds '10' at the end of last name.

vikas50_0-1711465087540.pngvikas50_1-1711465136282.pngvikas50_2-1711465165863.png