Add an user to a Group with a Business Rule?

ricardorodrigu1
Kilo Contributor

Hi everyone!

I have the followings requirements:

  1. Add a user to a Group based on specific conditions;
  2. If the user already exists on the group do not add another record with an update;
  3. If we have an update on the database and the user that exists on the group fail to match the specific conditions must be removed from the group;

I have created the following Business Rule on the [sys_user] Table:

      var rec1 = new GlideRecord('sys_user_grmember');

                rec1.initialize();  

                rec1.user = current.sys_id;  

                rec1.group.setDisplayValue('Testing');

                rec1.insert();

This script only answer to my first need (1), anyone can help me for the 2 and 3 requirements?

Thanks in advance,

Ricardo Rodrigues

1 ACCEPTED SOLUTION

Thanks for the update.


One more recommendation that please set filter condition in BR to fire only when title column is changed so that this is not fired everytime. Now add one more script block for your 3rd req.


if(current.title != 'IT') //Replace fieldcolumnname with exact column name


  {


  var rec1 = new GlideRecord('sys_user_grmember');


  rec1.addQuery('user', current.sys_id);


  rec1.addQuery('group.name', 'Testing');


  rec1.query();


  if(rec1.next())


  {


  rec1.deleteRecord();


  }


}


else


  {


  var rec1 = new GlideRecord('sys_user_grmember');


  rec1.addQuery('user', current.sys_id);


  rec1.addQuery('group.name', 'Testing');


  rec1.query();


  if(!rec1.next())


  {


  rec1.initialize();


  rec1.user = current.sys_id;


  rec1.group.setDisplayValue('Testing');


  rec1.insert();


  }


}


View solution in original post

14 REPLIES 14

Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

Hi Ricardo,



Here is the modifed BR


var rec1 = new GlideRecord('sys_user_grmember');


rec1.addQuery('user', current.sys_id);


rec1.addQuery('group.name', 'Testing');


rec1.query();


if(!rec1.next())


  {


  rec1.initialize();


  rec1.user = current.sys_id;


  rec1.group.setDisplayValue('Testing');


  rec1.insert();


}



Please elaborate further on your 3rd req.


Hi Pradeep,



I got the same code but how can we compare two whole records? The sys_id would be the same even if a field or two are changed right?


Thanks pradeepksharma and veena.kvkk88, it works perfectly



Do you have any ideia how to accomplish the third requirement? I already try some approaches but i didn't have success.


Can you please give more details on 3rd req. I am confused.