I'm trying to add Account team member dynamically but my code fires error msg.Please go through the steps below.
- Parent Account(Lookup Field) on Account Object
- VPA(Checkbox) on Account Object.
If VPA == true then the owner of parent account to which it is lookup should be added as account teammember on account page.
trigger AccountTeam on Account (after update) {
Integer newcnt = 0;
Integer newcnt0 = 0;
AccountTeamMember[] newmembers = new AccountTeamMember[]{};
//list of new team members to add
AccountShare[] newShare = new AccountShare[]{};
//list of new shares to add
Account a1 = [select id, parent.Id,Owner from account Where Id=:trigger.new[0].ParentID];
ID uid = a1.Owner;
//get the user id of the user running the trigger, anyone that changes the Account will added to the account team
for(Account a:trigger.new) {
AccountTeamMember Teammemberad=new AccountTeamMember();
Teammemberad.AccountId=a.id;
Teammemberad.UserId=uid;
Teammemberad.TeamMemberRole = 'Account Modifier';
newmembers.add(Teammemberad);
}
Database.SaveResult[] lsr = Database.insert(newmembers,false);
//insert any valid members then add their share entry if they were successfully added Integer newcnt=0;
for(Database.SaveResult sr:lsr) {
if(!sr.isSuccess()) {
Database.Error emsg =sr.getErrors()[0];
system.debug('\n\nERROR ADDING TEAM MEMBER:'+emsg);
} else {
newShare.add(new AccountShare(UserOrGroupId=newmembers[newcnt].UserId, AccountId=newmembers[newcnt].Accountid, AccountAccessLevel='Read',OpportunityAccessLevel='Read'));
}
newcnt++;
}
Database.SaveResult[] lsr0 =Database.insert(newShare,false);
//insert the new shares Integer newcnt0=0;
for(Database.SaveResult sr0:lsr0) {
if(!sr0.isSuccess()) {
Database.Error emsg0 = sr0.getErrors()[0];
system.debug('\n\nERROR ADDING SHARING:'+newShare[newcnt0]+'::'+emsg0);
}
newcnt0++;
}
}
Where Id=:trigger.new[0].ParentID
you should never write triggers that blindly grab data from the 0th record in the collection and presume that all records coming into the trigger are identical to the first one.