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

DirkRedeker
Mega Sage

Hi

First of all, I guess that your Business Rule is set active, but it will not fire... 

The Department is from  a reference table [cmn_department]. So your condition to run the business rule is wrong.

It should be :

current.Department.name.changesTo('CA')

Let me know if that answered your question and mark my answer as correct and helpful, please. 

BR 

Dirk 

No joy.