I have a trigger and a class that seem to be causing an insert fail in Dataloader. I am trying to insert 200 records to see if an error is generated before moving these to production. I'm just inserting the mandatory fields such as Name, Owner, Market, Customer_Success_Manager__c, and Business Unit.
Each time I get an error:
UpdateCSMTeam:execution of AfterInsertcaused by: System.DmlException: Insert failed. First exception on row 0 with id01MJ0000009gXthMAE; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]Class.UpdateCSM.updateTeamMem . I've listed the class and trigger below.
APEX CLASS
public class UpdateCSM {
public static void updateTeamMember(List<Account> accounts) {
List<AccountShare> ashareLIST = new List<AccountShare>();
List<AccountTeamMember> ATM = new List<AccountTeamMember>();
Set<String> rmMember = new Set<String>();
Map<ID, ID> acctToBRepMap = new Map<ID, ID>();
for(Account a:accounts){
AccountShare caSharingRule = new AccountShare();
caSharingRule.AccountId = a.Id;
caSharingRule.OpportunityAccessLevel = 'Edit';
caSharingRule.CaseAccessLevel = 'Edit';
caSharingRule.AccountAccessLevel = 'Edit';
caSharingRule.UserOrGroupId = a.Customer_Success_Manager__c;
ashareLIST.add(caSharingRule);
if(a.Customer_Success_Manager__c!= null){
AccountTeamMember Teammemberad=new AccountTeamMember();
Teammemberad.AccountId=a.id;
Teammemberad.UserId=a.Customer_Success_Manager__c;
Teammemberad.TeamMemberRole = 'Customer Success Manager';
ATM.add(Teammemberad);
if(!ATM.isEmpty()){
insert ATM;
insert ashareLIST;
if(a.Customer_Success_Manager__c==null){
list<AccountTeamMember> ratm = [SELECT UserId
FROM AccountTeamMember
WHERE (TeamMemberRole = 'Customer Success Manager')
AND AccountId =:a.id];
if(ratm.size()>0)
delete ratm;
}
}
}
}
}
}
...
APEX TRIGGER
trigger UpdateCSMTeam on Account (After update, After insert){
UpdateCSM.updateTeamMember(trigger.new);
}