7

Currently I have a trigger which auto-follows specific groups in our organization when a new user is brought onboard. The auto-follow trigger feature works great! However, we have quite a few groups we would like these users to follow, based on various departments, which means that the user will get emails for each of the groups they are added to. I would like to turn off email notifications during this process.

To do this, I found Database.DMLOptions.triggerUserEmail. This seems to be exactly what I am looking for, however the sending of th email persists. Below is the short function which is called by the trigger. As you can see, I tried adding the options to both the cand ChatterGroupMember object and to the database.insert. Using only one of these email header option sections also continues to send the email - as if it is being completely ignored.

Any assistance would be greatly appreciated.

/* Trigger */

    trigger User_AI on User(after insert, after update) {
        if(chatterAutoFollow.preventRecursive()) {

        // Run this only on insert
        if(Trigger.isInsert == true || Trigger.isUpdate == true) {

           /***********************************************************************************
             * Now let's add the users in the list who have their flag set for FLVSConnect groups
             ***********************************************************************************/

            // Get the users with their flag set
            Set<Id> followGroups = new Set<Id>();
            Set<Id> disableAllFeedsEmail = new Set<Id>();
            List<User> newUsersForGroups = [select Id, UserPreferencesDisableAllFeedsEmail from User 
                                    where Id in :trigger.newMap.keySet() 
                                      and Follow_FLVS_Connect_Groups_Now__c = true];

            // Since we are using a future method, let's put the users into the follow group set
            for(User newUser : newUsersForGroups) {
                followGroups.add(newUser.Id);
                if(newUser.UserPreferencesDisableAllFeedsEmail == true) {
                    disableAllFeedsEmail.add(newUser.Id);
                }
            }

            // now let's run the follow, but only if we have users that need to follow.
            if(followGroups.size() > 0) {
                ChatterAutoFollow.DisableChatterEmailFeeds(followGroups);
                ChatterAutoFollow.AddToGroups(followGroups);
                ChatterAutoFollow.ClearCheckBox('Follow_FLVS_Connect_Groups_Now__c',followGroups,disableAllFeedsEmail);            
            }
        }
}

/**** * Class called by the trigger: */

        public static void AddToGroups(Set<Id> userIds)
        {
            List<User> users = [select Id, Username from User where Id in :userIds];             
            Set<Id> updateUsers = new Set<Id>();
            // set up the groups that the user should be added to
            /*  All Users should be changed to the correct name of the group containing the department list */
            List<CollaborationGroup> chatterGroups=[select id, Name from CollaborationGroup where name like :ANNOUNCEMENT_GROUPS];

            // Start a new list that we can add new members to for the single update call.
            List<CollaborationGroupMember> chatterGroupMembers=new List<CollaborationGroupMember>();


        // loop the users - do not recheck for the flag, it may have already been updated!
        for (User user : users) {
            // loop the groups
            for (CollaborationGroup chatterGroup : chatterGroups) {
                // if is not already member, add the user to the group
                if(IsMember(chatterGroup.id, user.Id) == false) {

                    CollaborationGroupMember cand =
                        new CollaborationGroupMember(CollaborationGroupId=chatterGroup.id, MemberId = user.Id);

                    // Do not send an email to the users about the groups they're joining.
                    Database.DMLOptions dlo = new Database.DMLOptions();
                    dlo.EmailHeader.triggerAutoResponseEmail = false;
                    dlo.EmailHeader.triggerUserEmail = false;

                    // Set the email options on the user we're working with
                    cand.setOptions(dlo);

                    // Now add the user to the group list
                    chatterGroupMembers.add(cand);

                    // why did I do this?
                    updateUsers.add(user.Id);
                }
            }
        }
        // Only run the insert if needed
        System.Debug(chatterGroupMembers);

        // Do not send an email to the users about the groups they're joining.
        Database.DMLOptions dlo = new Database.DMLOptions();
        dlo.EmailHeader.triggerAutoResponseEmail = false;
        dlo.EmailHeader.triggerUserEmail = false;

        Database.insert( chatterGroupMembers, dlo);    
    }
  • 1
    I tried with ConnectAPI and same result - let me see if I can get someone on Chatter Team to respond... – BritishBoyinDC Oct 22 '14 at 15:32
  • The ConnectAPI team is looking into it to see if there is any options for you... – BritishBoyinDC Oct 24 '14 at 15:31
  • I edited the content to be more precise as to not allow the assumption that all steps that are already available through a google search have not been handled. – Ilene Jones Oct 28 '14 at 20:26
6
+25

Just did this for one of my orgs..

You need to update the users records setting UserPreferencesDisableAllFeedsEmail before adding them to the group

    list<User> inactiveNotificationUsers = new list<User>();
    set<Id> notificationUsers = new set<Id>();

    for (User u : [ SELECT ID
                           , UserPreferencesDisableAllFeedsEmail
                    FROM USER
                    WHERE UserPreferencesDisableAllFeedsEmail = false
                    AND ID IN:  YouUserIDs]  )
    {
        User ut = new User();
        ut.UserPreferencesDisableAllFeedsEmail = true;
        ut.Id = u.Id;
        inactiveNotificationUsers.add(ut);
        notificationUsers.add(u.Id);
    }

Then create the collaborationGroupMember for the users..

          CollaborationGroupMember groupMembership = new CollaborationGroupMember(
                    CollaborationGroupId = YourGroup.Id
                    , CollaborationRole = 'Standard'
                    , NotificationFrequency = 'D'
                    , MemberId = userId  );

Then you need to update the user and create the membership..

       if(!inactiveNotificationUsers.isEmpty())
        {
            update inactiveNotificationUsers;
        }

        if( !groupMemberships.isEmpty() )
        {
            insert groupMemberships; 
        }   

        resetEmailNotification( notificationUsers );

The final trick here is to reset the user's email notification.. You cannot do this during the same transaction so you need to call an @future method to get the email not fire.

@future
public static void resetEmailNotification( set<Id> userIds )
{
    system.debug('userIds: ' + userIds);

    list<User> notificationUsers = new list<User>();

    for (User u : [ SELECT ID
                           , UserPreferencesDisableAllFeedsEmail
                    FROM USER
                    WHERE ID IN: userIds ]  )
    {
        User ut = new User();
        ut.UserPreferencesDisableAllFeedsEmail = false;
        ut.Id = u.Id;
        notificationUsers.add(ut);
    }

    if(!notificationUsers.isEmpty())
    {
        update notificationUsers;
    }
}
  • Unfortunately this is already being done in the heart of my trigger, and is actually the model that I used to create the trigger code. In addition to the above, I have also added a check for recursive, so that the code is not run again during the update of the user. If the recursive check is not added, the trigger is put into an infinite loop as this is an update or insert trigger. – Ilene Jones Oct 28 '14 at 20:14
  • order of operations.. Your user update is not committed to database during after insert trigger. Don't set the UserPreferencesDisableAllFeedsEmail via a trigger and try to create a CollaborationGroupMember during same transaction. Do an user update as shown in example code. Yes you should be preventing recursion. salesforce.com/us/developer/docs/apexcode/Content/… – Benjamin Pirih Oct 28 '14 at 22:04

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.