Adding a role to user when added to a custom field

Luke James
Tera Contributor

Hello All, 

 

I have a requirement on the knowledge module, where on the knowledge category I have added a custom field, and when a user is added to the field it gives them the knowledge_manager role. Does anyone have a script to do this or know of the best way? Issue i'm getting in my script is that when one user is added it gives them the role, when I add another user after that it gives a unique key violation and removes the role from the user that is still in the field. 

 

Many Thanks, 

 

Luke

7 REPLIES 7

Danish Bhairag2
Tera Sage
Tera Sage

Hi @Luke James ,

 

Is that field a List type field or only reference field?

 

Thanks,

Danish

 

Hi @Danish Bhairag2 , 

 

Thanks for the reply. It's a list type field. 

 

Thanks, 

Luke

Can u share wht u have already done till now? @Luke James 

 

Thanks,

Danish

 

Hi @Luke James ,

 

You can try below BR code for this which should run after update

 

(function executeRule(current, previous /*, g*/) {

 

    var userList = current.custom_field; // Replace with the actual field name

 

    if (userList) {

        // Split the user list and iterate over each user

        var users = userList.split(',');

        for (var i = 0; i < users.length; i++) {

            var user = users[i].trim();

 

            // Check if the user exists and assign the role

            var userGr = new GlideRecord('sys_user_has_role');

            userGr.addQuery('user', user);

userGr.addQuery('role','knowledge_manager');

if(userGr.next()){

//Don't do anything

            }else{

userGr.initialize();

userGr.role = 'enter role sys I'd here';

userGr.user = user;

userGr.insert();

}

        }

    }

 

})(current, previous);

 

Thanks,

Danish