New to Apex and code in general so I would appreciate any recommendation on how I´m approaching this problem.
My Lead Object has a custom field utm_content__c
that will hold as value the Id of the campaign it should be related to.
So basically whenever a lead is updated and the custom field utm_content__c is not null it should trigger an apex class that creates a CampaignMember for that lead in that campaign.
Before creating the CampaignMember
I would like to check if it already exists. and get a list of those existing records.
That is very easy with flows using the Get element since every lead goes throug a single interview but I understand Apex Classes work with a list of Leads being updated at the same time. And it´s not recommended to perform DML actions inside for loops.
So would this approach be ok? It works but idk if there would be an easier way to get the same result.
public class crea_miembro {
public static list<CampaignMember> nuevoMiembro (List<Lead> leadsNew){
List<CampaignMember> members = new List<CampaignMember>();
Map<Id, String> partners = new Map<Id, String>();
Set<Id> LeadIds = new Set<Id>();
List<String> CampIds = new List<String>();
List <CampaignMember> allmatchingmembers = new List<CampaignMember>();
for(Lead leadActual:leadsNew){
partners.put(leadActual.Id, leadActual.utm_content__c);
LeadIds.add(leadActual.Id);
CampIds.add(leadActual.utm_content__c);
}
//Queries all campaignmembers based on all Lead Ids and all CampaignIds
allmatchingmembers.addAll([SELECT Id, LeadId, CampaignId FROM Campaignmember WHERE LeadId IN:LeadIds AND CampaignID IN: CampIds]);
//Keeps only the Campaign Member that share same LeadId and CampaignId.
for(Campaignmember member:allmatchingmembers){
if(member.CampaignId==partners.get(member.LeadId)){
members.add(member);
}
}
for(Campaignmember imprime: members){
System.debug(imprime.Id);
}
return members;
}
}