[SalesForce] How to check if the current user in Public groups before insert new contact using trigger

I have been trying to check the current user is exists in public groups or not using trigger on Contact object before insert. I was wondering whether this is right way to check it or not? Exactly what I want to achieve is to check and prevent current user from creating new contact which is not in particular groups. Any kind of suggestions are highly appreciated. Here is my trigger:

  trigger ValidateUserToImport on Contact (before insert) {



public String Currentusergroup {get;set;}

   List<groupmember> lst = [select group.name,group.DeveloperName from groupmember where UserOrGroupid=:UserInfo.getUserId()];
   //List<Contact> contacts = [select Home_Company__c, Working_Host_Company__c from Contact];

  for( Contact c : trigger.new )
  {
     for(groupmember lst2: lst)
      {
        if(c.Working_Host_Company__c != lst[0].group.DeveloperName)
        {
            c.addError('Insufficient rights');
        }
        else
      {
        insert c;
      }
      }

  }

}

I tried like this, still wondering whether this is right way to do as follows:

trigger ValidateUserToImport on Contact (before insert) {

  public String Currentusergroup {get;set;}

   List<groupmember> lst = [select group.name,group.DeveloperName from groupmember where UserOrGroupid=:UserInfo.getUserId()];
   List<Contact> work_cmpny = [select Home_Company__c, Working_Host_Company__c from Contact];

  for( Contact c : trigger.new )
  {
     for(groupmember lst2: lst)
      {
        if(!c.Working_Host_Company__c.Contains(lst2.group.DeveloperName))
        c.addError('Insufficient rights');
      }
  }

}

Best Answer

You could do something like the following (untested) code. It is building a Set of all the groups the current user is in. It will then check each Working_Host_Company__c on the Contact, if the user is not in a group for that Contact then an error is added.

   Set<String> groupNames = new Set<String>();
   for (GroupMember gm : [select 
                             group.name,
                             group.DeveloperName 
                          from GroupMember 
                          where UserOrGroupId = :UserInfo.getUserId()]) {
       groupNames.add(gm.group.DeveloperName);
   }

   for(Contact c : trigger.new) {
      if (!groupNames.contains(c.Working_Host_Company__c)) {
           c.addError('Insufficient rights');
      }
   }
Related Topic