I need to develop Apex code to allow team members to auto-follow in Chatter when they are added to the Account. Team members are added to fields, and our consultant developed code to push the field information to the Account Team. I want to use the field inputs, instead of the Account Team, to build out our auto-follow team. I recently took the DEV 501 course, and included in the course is a great guideline for auto-follow. I'm trying to adapt that code for our purposes, but am not experienced enough to get around my issue.
Managing_Director_lu__c, Underwriting_Director__c, and Claims_Manager_lu__c are all custom lookup fields to the User object. All three fields will be populated, and all three team members will need to auto-follow simultaneously.
Apex Class:
public class AutoFollowOrgs {
public static void OrgTeamSubscribeOrg(List <Account> accts) {
System.Debug('OrgTeamSubscribeOrg: Entering');
List<EntitySubscription> subscriptions = new List <EntitySubscription>();
for (Account acct: accts) {
EntitySubscription eSubs = new EntitySubscription(ParentId = acct.Id);
if(acct.Managing_Director_lu__c != NULL){
eSubs.SubscriberId = acct.Managing_Director_lu__c;
}
subscriptions.add(eSubs);
if(acct.Underwriting_Director__c != NULL){
eSubs.SubscriberId = acct.Underwriting_Director__c;
}
subscriptions.add(eSubs);
if(acct.Claims_Manager_lu__c != NULL){
eSubs.SubscriberId = acct.Claims_Manager_lu__c;
}
subscriptions.add(eSubs);
}
try {
Database.insert(subscriptions);
}
catch (DMLException dmlEx) {
//if we get an error because this user is already following this object, it's okay.
if (dmlEx.getDmlType(0) == statusCode.DUPLICATE_VALUE) {
System.Debug('OrgTeamSubscribeOrg: subscription already exists');
} else {
//otherwise we have a more serious error that we need to throw.
throw dmlEx;
}
}
}
}
I believe the issue lies with my subscriptions.add(eSubs) code. If I place it at the end of all the IF statements, only the last team member is added. This makes sense because I realized I was basically replacing the ParentID and SubscriberId with each IF statement. So, I tried adding the line after each IF statement, and get the following error when I run the code:
Error:Apex trigger AutoFollowOrgsTrigger caused an unexpected exception, contact your administrator: AutoFollowOrgsTrigger: execution of AfterUpdate caused by: System.ListException: Before Insert or Upsert list must not have two identically equal elements: Class.AutoFollowOrgs.OrgTeamSubscribeOrg: line 28, column 1
Okay, I guess this also makes sense because I must still only adding data to one line in the list, not multiple lines.
How do I adapt my code so that each team member is a different row in the list? Thanks!