0

I have this trigger where it adds new user to chatter group but it throws exceptions everytime when i reset the password or when i deactivate any user, how can i update the trigger to not throw any exceptions?

Trigger:

trigger CompanyChatter on User (after insert, after update) {
    UserMethods.addToMainGroup(trigger.newMap.keySet());
}

Apex class:

public class UserMethods {

    @future
    public static void addToMainGroup(Set<Id> userIds) {
     List<User> users=[select id, Username from User where id in :userIds];

     CollaborationGroup chatterGroup=[select Id from CollaborationGroup Where Name='My Company, Inc'];
     List<CollaborationGroupMember> chatterGroupMembers=new List<CollaborationGroupMember>();

     for(User user: users){
         CollaborationGroupMember newMember = new CollaborationGroupMember(CollaborationGroupId=chatterGroup.id, MemberId = user.Id, NotificationFrequency = 'P');
         chatterGroupMembers.add(newMember);
     }
    if(!Test.isRunningTest()){
     insert chatterGroupMembers;
     }
    }

}

Exceptions

For Reset passwords:

Developer script exception from SonoSite, Inc : 'UserMethods' for job id '7073300002yuF1b' : Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, User is already a Member of this group.: [MemberId]

When i deactivate users:

First error: Insert failed. First exception on row 0; first error: INACTIVE_OWNER_OR_USER, operation performed with inactive user [00540000002ome5]

2

You need to filter your User records so you only create a CollaborationGroupMember when one is appropriate. That involves two steps:

  1. Make sure the User record is active.
  2. Make sure there is no associated CollaborationGroupMember.

You can verify both of the above by modifying the SOQL for your User query.

List<User> users = [
    SELECT Id FROM User WHERE Id IN :userIds AND IsActive = true AND Id NOT IN (
        SELECT MemberId FROM CollaborationGroupMember
        WHERE CollaborationGroup.Name = 'My Company, Inc'
    )
];
  • How can i just modify above trigger to avoid exceptions? – Admin_BA Apr 27 '16 at 22:30
  • @Admin_BA Why can't you modify the class? Regardless, I added how you can use Apex to get what you need. – Adrian Larson Apr 27 '16 at 22:30
  • Sorry i didn't meant to downvote, iam still new to this site. How do i modify my existing class to include this? i didn't meant trigger – Admin_BA Apr 27 '16 at 22:47
  • @Admin_BA You just put the query inside your square brackets. List<User> users = [/*query*/]. – Adrian Larson Apr 27 '16 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.