Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- trigger Addtogroup1 on Contact (after insert, after update) {
- List<GroupMember> GMlist = new List<GroupMember>();
- Set<String> contactEmails = new Set<String>();
- for(Contact con : Trigger.New) {
- //create a set with the contact email addresses
- contactEmails.add(con.email);
- }
- //query for the related users and put them in a map,
- //where the key is the email and the value is the user
- Map<String, User> emailUserMap = new Map<String, User> ();
- for(User aUser : [select id, email from User where email in : contactEmails]){
- emailUserMap.put(aUser.email, aUser);
- }
- system.debug(emailUserMap);
- List<Id> userIdList = new List<Id>();
- for(Contact con : Trigger.New) {
- if(con.Public_Group_Service_Partner_Content1__c == TRUE) {
- userIdList.add(emailUserMap.get(con.email).id);
- }
- }
- //dymanically get the get group id.
- Group theGroup = [select id from Group where Name = 'Service Partner Content'];
- if(null != theGroup){
- //call the contact trigger helper if the group exists.
- //This method adds the user to the group
- ContactTriggerHelper.addUsersToGroup(theGroup.id,userIdList );
- }
- public class ContactTriggerHelper{
- //future call to do the group adding. the future call will spawn a new thread.
- @future
- public static void addUsersToGroup(String groupId, List<Id> userIds){
- List<GroupMember> GMlist = new List<GroupMember>();
- for(ID userId: userIds){
- GroupMember gm = new GroupMember();
- gm.GroupId = groupId;
- gm.UserOrGroupId = userId;
- gmList.add(GM);
- }
- if(gmList.size() > 0){
- insert gmList;
- }
- }
- @isTest
- // Insert contact with your required field.
- Contact cnt = new Contact();
- cnt.LastName = 'Test contact';
- cnt.Email = 'test@test.com';
- cnt.Public_Group_Technology_Partner_Content__c = true;
- insert cnt;
- // Insert user
- Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
- User u = new User(Alias = 'standt', Email='test@test.com',
- EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
- LocaleSidKey='en_US', ProfileId = p.Id,
- TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
- insert u;
- // Insert Group
- if(isGroup == true)
- {
- Group grp = new Group();
- grp.Name = 'Technology Partner Content';
- grp.DeveloperName = 'Technology Partner Content';
- insert grp;
- }
- }
- static testMethod void insertWithGroup()
- {
- createGroup(true);
- }
- static testMethod void insertWithoutGroup()
- {
- createGroup(false);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement