Add User to Group with Business Rule

John Shores1
ServiceNow Employee
ServiceNow Employee

During our nightly LDAP feed into sys_user, I need to check what department a user is in. If they're in a specific department, I need to add them to a group (if they're not already a member). I've created an advanced business rule on sys_user to run after insert or update with the condition:

current.department.changesTo('CA')

The script is

(function executeRule(current, previous /*null when async*/) {
	
	//sys_id of group
	var myGroup = '3b8123654f477b40d8a4ea7d0210c7ca';
	
	var gr = new GlideRecord('sys_user_grmember');
	gr.addQuery('group', myGroup);
	gr.addQuery('user', current.sys_id);
	gr.query();
	
	if(!gr.next()) {
		gr.initialize();
		gr.group = myGroup;
		gr.user = current.sys_id;
		gr.insert();
	}
	
})(current, previous);

When I run this code in Xplore and force a user's sys_id into current.sys_id, it works as expected, but the business rule isn't doing anything when a user's record is created or updated.

Anything stick out about this that would make it not work?

7 REPLIES 7

siva_
Giga Guru

Xplore runs the code without any condition check , so in this case , there might be an issue with teh condition specified 

Just remove the condition and try to create / update a user record and check if that is working 

If working, then there need to be some error in the condition , you can log the condition inside the script to check whether its returning trur or undefined or so... 

 

Thanks,

Siva

Mark this response as correct if that really helps

John Shores1
ServiceNow Employee
ServiceNow Employee

Yep, I understand that. I tested the code in Xplorer just to determine whether the record would be created if the conditions were met.  Which it was.

VigneshMC
Mega Sage

In your transform map for LDAP feed, have you checked run business rule field?

find_real_file.png

 

and also department is an reference field, please use sys_id instead of name in the condition

Haven't gotten that far yet. I'm simply testing by manually modifying the user record and updating it.