Business Rule to remove/add users from sys_user_group based on "u_department" value.

Aki17
Kilo Guru

When "u_department" value of sys_user record is changed, I would like that user to be removed from the OLD group and then added to the NEW group.

For example, when an user's [u_department] value is changed from "Dep-A" to "Dep-B", the user should be removed from "Dep-A" sys_user_group and then added to "Dep-B" sys_user_group automatically.

I believe that After/Update Business Rule is required, but I'm not very familiar with scripting, so could someone please give me the sample BR for this?

 Best Regards,

Aki

 

1 ACCEPTED SOLUTION

Hi,

so u_department holds group name then do this

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

    // Add your code here
    var gr = new GlideRecord("sys_user_grmember");
    gr.addQuery("group.name", previous.u_department);
    gr.addQuery("user", current.getUniqueValue());
    gr.query();
    if (gr.next()) {
        gr.deleteRecord();

        var gr1 = new GlideRecord("sys_user_grmember");
        gr1.initialize();
        gr1.setDisplayValue('group',current.u_department);
        gr1.user = current.getUniqueValue();
        gr1.insert();
    }

})(current, previous);

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

9 REPLIES 9

Hi,

so u_department holds group name then do this

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

    // Add your code here
    var gr = new GlideRecord("sys_user_grmember");
    gr.addQuery("group.name", previous.u_department);
    gr.addQuery("user", current.getUniqueValue());
    gr.query();
    if (gr.next()) {
        gr.deleteRecord();

        var gr1 = new GlideRecord("sys_user_grmember");
        gr1.initialize();
        gr1.setDisplayValue('group',current.u_department);
        gr1.user = current.getUniqueValue();
        gr1.insert();
    }

})(current, previous);

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Hi Ankur,

Thank you so much! It worked for String field type!

Hi Ankur,

Thank you so much for your script! It worked for the String field type!

However, do you have any idea to deal with the discrepancy between [u_department] value (Dep-A, Dep-B, Dep-C...) and Group (sys_user_group) records name (Dep-AG, Dep-BG, Dep-CG... )?

 

Glad to know.

Please mark my response as correct and helpful to close the thread.

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Hi,

if your group names having the suffix as G in their name in sys_user_group then you need to accordingly set the value

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader