+ Start a Discussion
MattyDHLMattyDHL 

Trigger - Loop Query to delete records?

 Hi,

 

I am currently stuck on a trigger. I have 2 Lists which I want to loop through to delete all the record matching the criteria.

 

I would like to loop through to create a List of AccountShare records with the values in LAccId and LUserId. The query will look something like this:


List<AccountShare> accsharedel = [SELECT Id FROM AccountShare where (AccountId =  LAccId AND UserOrGroup = LUserId)];

 

How can I loop through the LAccId list and the LUserId list to populate the accsharedel list which I can then delete?


Thanks in advance.

 

 

 

trigger UpdateTeamMembers on Account (before update) { AccountTeamMember[] newmembers = new AccountTeamMember[]{}; //list of new team members to add AccountShare[] newShare = new AccountShare[]{}; //list of new shares to add Integer delcnt=0; List<String> LAccId = new List<String>(); List<String> LUserId = new List<String>(); for(Account a:trigger.new){ if (trigger.old[0].X2ndOwnerTM__c != a.X2ndOwnerTM__c ){ AccountTeamMember Teammemberad=new AccountTeamMember(); Teammemberad.AccountId=a.id; Teammemberad.UserId=a.X2ndOwnerTM__c; Teammemberad.TeamMemberRole = a.X2ndOwnerRole__c; newmembers.add(Teammemberad); LAccId.add(delcnt,a.id); LUserId.add(delcnt,a.X2ndOwnerTM__c); delcnt++; } } List<AccountTeamMember> DelATM = new List<AccountTeamMember>(); List<AccountShare> DelAS = new List<AccountShare>();

 

 

 

jkucerajkucera

I'm a bit confused with what you are asking - seems like you populated LAccID list from Trigger.new.Id and you populate LUserId from Trigger.new.Owner.  I think you'd rather have a Map that has both:

 

Map<Id, Id> AccIdToUserIdMap=new Map<Id,Id>(); AccIdToUserIdMap.put(a.Id, a.X2ndOwnerTM__c);

 

 

Is AccountShare a custom object you have that has AccountId and UserId (owner) as fields that you are looking to match?

 

If so, you can query AccountShare to get the AccountId matches & then loop through the results for the UserId matches:

 

 

List<AccountShare__c> delAS=new List<AccountShare__c>(); List<AccountShare__c> as=[Select Id, UserOrGroup FROM AccountShare__c WHERE AccountId IN :lAccId]; For (AccountShare__c as1:as){ if (as1.OwnerId=AccIdToUserIdMap.get(as1.AccountId)){ delAS.add(as1); } } delete delAS;

 

 

MattyDHLMattyDHL

Hi,


Thanks for the info,I feel a little stupid now. Not exactly what I need but put me in the right direction.

 

Again, thanks.

 

Matt