logo

NJP

Widget for letting user add themself to a group

Import · Mar 23, 2017 · article

I have created a small widget that allows a user to add or remove themself from a group.

This is in large part borrowed from Create custom action buttons in Service Portal - ServicePortal.io - Service Portal, CMS, and Custom ...

The reason I add it to the community is that I found an interesting "feature" in ServiceNow that may confuse some.

When removing themselves from a group, regardless if this means changes in rolls and skills, the user will see the RoleManager Script Include info messages.

I fixed this by adding gs.flushMessages(); to the remove part.

Code for page:

Group membership
Add me Remove me

Code for Client:

function() {

  var c = this;

      c.uiAction = function(action) {

              c.data.action = action;

              c.server.update().then(function() {

                      c.data.action = undefined;

              })

      }

}

Code for server:

(function() {

      //Get user sys_id

      var me = gs.getUserID();

//If input from button, get which input

      if (input && input.action) {

              var action = input.action;

//If Add, check that user is not member and then add them

              if (action == 'add') {

                      var nydi = new GlideRecord('sys_user_grmember');

                      nydi.addQuery('user',me);

                      nydi.addQuery('group','sys_id of group');

                      nydi.query();

                      if(!nydi.next())

                      {

                              nydi.initialize();

                              nydi.user = me;

                              nydi.group = 'sys_id of group';

                              nydi.insert();

                              gs.addInfoMessage('You have been added to the group.');

                      }

              }

//If remove, check that user is member of the group then remove them.

              if (action == 'remove') {

                      var hardi = new GlideRecord('sys_user_grmember');

                      hardi.addQuery('user',me);

                      hardi.addQuery('group','sys_id of group');

                      hardi.query();

                      while(hardi.next())

                      {

                              hardi.deleteRecord();

                              gs.flushMessages();

                              gs.addInfoMessage('You are no longer a member of the group.');

                      }

              }

      }

})();

View original source

https://www.servicenow.com/community/developer-articles/widget-for-letting-user-add-themself-to-a-group/ta-p/2330220