Business Rule to Assign Role on Insert into sys_user table with conditions

Scott Megargee
Tera Expert

I have a request alter code for assigning as specific role to a user when inserted into the sys_user table. My current code works as expected but it's applying to "all users" inserted and now I need it to filter out specific records.

 

Current Code:

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

var appRole = new GlideRecord('sys_user_has_role');
appRole.initialize();
appRole.user = current.sys_id;
appRole.role = 'sys_id_of_role'; // role sys_id for xyz appRole.insert();

})(current, previous);

I need this to filter out users where -

1. sys_user - Employee number is not empty, and Class is User

2. sys_user_group - User is not a member of xyz group. 

 

How can I incorporate these requirements into my current code? 

1 ACCEPTED SOLUTION

Anubhav24
Mega Sage
Mega Sage

Hi @Scott Megargee ,

For your filter conditions you can first query on sys_user_grmember table in this table you add a filter of your group and also dot walk using user fields in your case employee number and class since user is reference on this column, at the same time you can use the sample encoded query to build your query "user.active=true^user.cityISNOTEMPTY^group=e948597ef7ecf810ec1c41b84851e0a7"

If this query returns records then you can proceed ahead with your code of assigning the role to the intended user.

View solution in original post

5 REPLIES 5

Mark Roethof
Tera Patron
Tera Patron

Hi there,

 

Don't see a reason why to change your code.

 

Have you looked at changing the conditions?

 

Kind regards,

 

Mark Roethof

Independent ServiceNow Consultant

10x ServiceNow MVP

---

 

~444 Articles, Blogs, Videos, Podcasts, Share projects - Experiences from the field

LinkedIn

Basically, I only want to run the code if a record inserted into sys user table meets the new conditions I noted. I don't really have a lot of flexibility when it comes to changing the conditions/requirements for when the code should run. 

I don't understand, why wouldn't you have flexibility in changing the conditions of the business rule? That would even be a best practice, over doing such in your script since your script would simply trigger unnecessary.

 

Kind regards,

 

Mark Roethof

Independent ServiceNow Consultant

10x ServiceNow MVP

---

 

~444 Articles, Blogs, Videos, Podcasts, Share projects - Experiences from the field

LinkedIn

Mark Roethof
Tera Patron
Tera Patron

You might also consider newer techniques for requirements like these... Flow Designer. Zero code involved when I look at what you are asking.

 

Kind regards,

 

Mark Roethof

Independent ServiceNow Consultant

10x ServiceNow MVP

---

 

~444 Articles, Blogs, Videos, Podcasts, Share projects - Experiences from the field

LinkedIn