Adding a role to user when added to a custom field
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-26-2023 11:43 AM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-26-2023 11:47 AM
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-26-2023 11:51 AM
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-26-2023 11:55 AM
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-26-2023 12:03 PM
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