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 eachWorking_Host_Company__c
on theContact
, if the user is not in a group for thatContact
then an error is added.