In some catalog items, you want to check if a member is already part of a group he wants to join or not. This could have various reasons, one of them might be you want to automate adding group membership to users via requests. To avoid errors you want to check if a member is already in that group and prevent submission of that request. Usually, you are using catalog client scripts to fulfill that requirement. There you can either do the query client-side via GlideRecord or you can call a script include to speed up performance. I would like to show you the way with the script include.
Script Include
var tlgr_GroupUtil = Class.create(); tlgr_GroupUtil.prototype = Object.extendsObject(AbstractAjaxProcessor, { getGroupMembers: function(group, query) { group = group || this.getParameter('sysparm_group'); query = query || this.getParameter('sysparm_query'); if (JSUtil.nil(group)) { return ''; } //query is optional, if nil, set it empty to have encoded query running if (JSUtil.nil(query)) { query = ''; } var arr = []; var retObj = {}; var grm = new GlideRecord('sys_user_grmember'); grm.addQuery('group', group); grm.addEncodedQuery(query); grm.query(); while (grm.next()) { retObj.sys_id = grm.getValue('user'); retObj.name = grm.user.name.toString(); arr.push(retObj); retObj = {}; } return JSON.stringify(arr); }, type: 'tlgr_GroupUtil' });
Catalog Client Script
function onChange(control, oldValue, newValue, isLoading) { if (isLoading || newValue == '') { return; } var ga = new GlideAjax('tlgr_GroupUtil'); ga.addParam('sysparm_name', 'getGroupMembers'); ga.addParam('sysparm_group', g_form.getValue('select_group')); ga.getXML(checkGroupMembers); //callback function function checkGroupMembers(response) { var answer = response.responseXML.documentElement.getAttribute("answer"); if (answer != '') { // Do Something if user is already in group. In this case set value to blank g_form.setValue('select_group',''); } }
Of course, you might need to modify the catalog client script a little bit to your requirements but in general, this should already work pretty well.
I was trying to use this code but is not working. It always return that the user is already part of the group event is not.