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 CompanyChatter on User (after insert, after update) {

Apex class:

public class UserMethods {

    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');
     insert chatterGroupMembers;



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]


1 Answer 1


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, 2016 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, 2016 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, 2016 at 22:47
  • @Admin_BA You just put the query inside your square brackets. List<User> users = [/*query*/].
    – Adrian Larson
    Apr 27, 2016 at 22:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .