how to auto assign role to user.

Akansh
Tera Contributor

 i have a requirement where in a table there is a user reference field. i want to auto assigned role to a user when the that user field is populated.

1 ACCEPTED SOLUTION

AakashGarg1678
Kilo Guru

Hi @Akansh,

Hope you are doing well.

 

I got your requirement clearly as you want to automatically assign role(s) based on user selection (which is of reference type field) 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

Pre-requisites/Consideration: -

1. Logic will trigger on change of User Field available on the form.

2. Role(s) will be provided by the person who is modifying the form.

3. Role(s) will be added by the person in a prompt field.

 

There are just 2 basic steps you need to follow to achieve this task/requirement as mentioned below: -

Step1 - Create a new "On Change" Client Script that will trigger the script/implementation as soon as user field get changed by someone on the form. You have to make a "GlideAjax" call.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    //Type appropriate comment here, and begin script below
    //    alert('Hi');
    var arr = prompt('What role(s) you want to give to the assigned user? Add roles with commas'); // This will give the prompt to enter the roles you want to assign to the user.
    // alert(arr);
    // alert(typeof arr);
	// alert(g_form.getValue('u_my_user'));
    var ga = new GlideAjax('global.AssignRolesToUser'); // GlideAjax Call
    ga.addParam('sysparm_name', 'getCampus'); // Calling Function
    ga.addParam('sysparm_user', g_form.getValue("u_my_user")); // Passing User value
    ga.addParam('sysparm_role', arr); // Passing Role(s)
    ga.getXML(updateCampus);

    function updateCampus(response) {
        var answer = response.responseXML.documentElement.getAttribute("answer"); // Getting Response
        // var clearvalue; // Stays Undefined
        if (answer) {
            alert("Successfully Assigned Roles to the User");
            // var returneddata = answer.evalJSON(true);
            // g_form.setValue("campus", returneddata.sys_id, returneddata.name);
            // } else {
            // g_form.setValue("campus", clearvalue);
        }
    }
}

 

Step2 - Create a new "Client Callable" Script Include to insert the new records in "User Roles (sys_user_has_role)" table as this table contains and store the mapping of User and Roles associated with the users.

var AssignRolesToUser = Class.create();
AssignRolesToUser.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    getCampus: function() {
        var arr = [];
        var user = this.getParameter('sysparm_user');
        var role = this.getParameter('sysparm_role').split(',');
        for (var i = 0; i < role.length; i++) {
            var find_role = new GlideRecord('sys_user_role');
            find_role.addQuery('name', role[i]);
            find_role.query();
            if (find_role.next()) {
                var gr = new GlideRecord('sys_user_has_role');
                gr.initialize();
                gr.user = user;
                gr.role = find_role.sys_id;
                arr.push(gr.insert());
            }
        }
        return true;
    },
    type: 'AssignRolesToUser'
});

 

Outputs: - You can check your output by navigation to User Roles (sys_user_has_role) table before and after the implementation.

 

For your reference, kindly find the snapshots of the scripts (Client Scripts and Script Include) and others that you can try on your instance and assuring you this will really gonna meet and solve your requirement.

 

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

 

Thanks

Aakash Garg

ServiceNow Developer

View solution in original post

3 REPLIES 3

Mark Manders
Mega Patron

What kind of table is this? This sounds more like you should create a catalog item or record producer for this, apply approval logic and then assign the role.

You aren't providing much information, but just filling a user on a form and with that assigning a role, doesn't sound very audit-proof.


Please mark any helpful or correct solutions as such. That helps others find their solutions.
Mark

Dr Atul G- LNG
Tera Patron
Tera Patron

Hi @Akansh 

 

Seems half information you provided. is it you want to do via catalog item or flow or inbound action ? please elaborate more. 

*************************************************************************************************************
If my response proves useful, please indicate its helpfulness by selecting " Accept as Solution" and " Helpful." This action benefits both the community and me.

Regards
Dr. Atul G. - Learn N Grow Together
ServiceNow Techno - Functional Trainer
LinkedIn: https://www.linkedin.com/in/dratulgrover
YouTube: https://www.youtube.com/@LearnNGrowTogetherwithAtulG
Topmate: https://topmate.io/atul_grover_lng [ Connect for 1-1 Session]

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

AakashGarg1678
Kilo Guru

Hi @Akansh,

Hope you are doing well.

 

I got your requirement clearly as you want to automatically assign role(s) based on user selection (which is of reference type field) 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

Pre-requisites/Consideration: -

1. Logic will trigger on change of User Field available on the form.

2. Role(s) will be provided by the person who is modifying the form.

3. Role(s) will be added by the person in a prompt field.

 

There are just 2 basic steps you need to follow to achieve this task/requirement as mentioned below: -

Step1 - Create a new "On Change" Client Script that will trigger the script/implementation as soon as user field get changed by someone on the form. You have to make a "GlideAjax" call.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    //Type appropriate comment here, and begin script below
    //    alert('Hi');
    var arr = prompt('What role(s) you want to give to the assigned user? Add roles with commas'); // This will give the prompt to enter the roles you want to assign to the user.
    // alert(arr);
    // alert(typeof arr);
	// alert(g_form.getValue('u_my_user'));
    var ga = new GlideAjax('global.AssignRolesToUser'); // GlideAjax Call
    ga.addParam('sysparm_name', 'getCampus'); // Calling Function
    ga.addParam('sysparm_user', g_form.getValue("u_my_user")); // Passing User value
    ga.addParam('sysparm_role', arr); // Passing Role(s)
    ga.getXML(updateCampus);

    function updateCampus(response) {
        var answer = response.responseXML.documentElement.getAttribute("answer"); // Getting Response
        // var clearvalue; // Stays Undefined
        if (answer) {
            alert("Successfully Assigned Roles to the User");
            // var returneddata = answer.evalJSON(true);
            // g_form.setValue("campus", returneddata.sys_id, returneddata.name);
            // } else {
            // g_form.setValue("campus", clearvalue);
        }
    }
}

 

Step2 - Create a new "Client Callable" Script Include to insert the new records in "User Roles (sys_user_has_role)" table as this table contains and store the mapping of User and Roles associated with the users.

var AssignRolesToUser = Class.create();
AssignRolesToUser.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    getCampus: function() {
        var arr = [];
        var user = this.getParameter('sysparm_user');
        var role = this.getParameter('sysparm_role').split(',');
        for (var i = 0; i < role.length; i++) {
            var find_role = new GlideRecord('sys_user_role');
            find_role.addQuery('name', role[i]);
            find_role.query();
            if (find_role.next()) {
                var gr = new GlideRecord('sys_user_has_role');
                gr.initialize();
                gr.user = user;
                gr.role = find_role.sys_id;
                arr.push(gr.insert());
            }
        }
        return true;
    },
    type: 'AssignRolesToUser'
});

 

Outputs: - You can check your output by navigation to User Roles (sys_user_has_role) table before and after the implementation.

 

For your reference, kindly find the snapshots of the scripts (Client Scripts and Script Include) and others that you can try on your instance and assuring you this will really gonna meet and solve your requirement.

 

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

 

Thanks

Aakash Garg

ServiceNow Developer