Auto-add users to group if the user is added to a certain role

atul_05
Tera Contributor

Hello Team,

I have requirement that when a user is added to a role then they should automatically be added to a group

Example: If xyz user is added to "knowledge" role then xyz should be added to "KM Dashboard" group.

 

Can you help how can I achieve this.

6 REPLIES 6

hi,

 

That requires knowledge of the table and field name to "check if the user is of a certain Business Unit and in this case if the user is from KPOE Business unit then only he should be added." Logic can be added to the script to check that if table, field name, and value are known.

 

And you can comment out or delete any lines in my example as you desire. Those are for debug while testing.

Bert_c1
Kilo Patron

Hi @atul_05 , I see a table named 'business_unit' in my instance. But I don't see how a user is associated with a record there. I would expect a Reference field on the sys_user table for the "Business Unit" table.  If that is what you have, then updated script logic is:

 

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

	// Add your code here
	var roleName = current.role.getDisplayValue();
	var userID = current.user;
	
	// logic to add user to group if assigned the knowledge role and associated with a specific
	// business unit. Repeat for each role and group desired

	// Test bu sys_id: 9ccc0c94972221101dd3fa67f053af69, use the following 'if' statement if there
	// is a custom reference field on sys_user for the user's business unit. 
//	if ((roleName == 'knowledge') &&
//		(current.user.u_business_unit == '9ccc0c94972221101dd3fa67f053af69')
//       ) {

	if (roleName == 'knowledge') {
		gs.addInfoMessage("User: " + userID.getDisplayValue() + " now has role: " + roleName);
		var grpMember = new GlideRecord('sys_user_grmember');
		grpMember.addQuery('user', userID.toString());
		grpMember.addQuery('group', 'KM Dashboard');
		grpMember.query();
		gs.addInfoMessage("Found " + grpMember.getRowCount() + " records for user: " + userID + " and group KM Dashboard");
		if (grpMember.getRowCount() == 0) {
			gs.addInfoMessage("Will add " + userID + " to group KM Dashboard");
			var groupID = '995e2333975221101dd3fa67f053af59'; // sys_id of KM Dashboard Group
			addUserToGroup(userID, groupID);
		}
	}
	
	function addUserToGroup(usrID, grpID) {
		grpMember.initialize();
		grpMember.user = usrID;
		grpMember.group = grpID;
		return grpMember.insert();
	}

})(current, previous);