Help with Business Rule

Thomas99
Tera Contributor

Can someone please help me with a BR to add users to a group? 

 

If a user is active and is not a party of " All users" group, then add him/her to the group. 

 

I created a BR rule using sys_user table with the following condition, but I need help with the code.  Also, I prefer to run this business rule when there is an update in the user record only, so I'm assuming I will check only "Update" 

 

Active = True

Created by = Azure 

1 ACCEPTED SOLUTION

Sainath N
Mega Sage

@Thomas99 : Here is the code that worked in my PDI. It's an after-update business rule with the conditions you mentioned.

 

 

 

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

    var gr = new GlideRecord('sys_user_grmember'); // Table stores the mapping of user and group.
    gr.addQuery('user', current.sys_id.toString()); // sys_id of user.
    gr.addQuery('group', '<sys_id_group>'); // replace <sys_id_group> with actual sys_id of group.
    gr.query();

    if (!gr.next()) {
        gs.info("User is Not a Member of Group!");
        // Logic to add to group
        gr.initialize();
        gr.user = current.sys_id.toString();
        gr.group = '<sys_id_group>';
        gr.insert();
    }

})(current, previous);

 

 

sainathnekkanti_5-1704320097185.png

 

Please mark this as correct answer and helpful if it resolved, or mark this helpful if this help you to reach towards solution.

View solution in original post

4 REPLIES 4

Sainath N
Mega Sage

@Thomas99 : Here is the code that worked in my PDI. It's an after-update business rule with the conditions you mentioned.

 

 

 

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

    var gr = new GlideRecord('sys_user_grmember'); // Table stores the mapping of user and group.
    gr.addQuery('user', current.sys_id.toString()); // sys_id of user.
    gr.addQuery('group', '<sys_id_group>'); // replace <sys_id_group> with actual sys_id of group.
    gr.query();

    if (!gr.next()) {
        gs.info("User is Not a Member of Group!");
        // Logic to add to group
        gr.initialize();
        gr.user = current.sys_id.toString();
        gr.group = '<sys_id_group>';
        gr.insert();
    }

})(current, previous);

 

 

sainathnekkanti_5-1704320097185.png

 

Please mark this as correct answer and helpful if it resolved, or mark this helpful if this help you to reach towards solution.

Thank you! 

Mark Roethof
Tera Patron
Tera Patron

Hi there,

 

"but I need help with the code". Did you consider using Flow Designer for this? Newer way of working, and for your use case most likely zero code involved.

 

Kind regards,

 

Mark Roethof

Independent ServiceNow Consultant

10x ServiceNow MVP

---

 

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

LinkedIn

Hi Mark...

 

Thank you. I did a test with flow designer and, yes it should work too 🙂 Thanks for the code-free suggestion. 

 

Snedden