+ Start a Discussion
KevSnellKevSnell 

Query if Lead is in Campaign by matching Custom Lead Field

Hi All.

 

I'm hoping someone can help with this simple fix.

 

I have the following code below that looks at a lead field called custom field hubspot_campaign_c (this has a campaign ID in) and if it is not null it adds the lead to the specific campaign listed in hubspot_campaign_c.

 

trigger LeadToCampaign on Lead (after update, after insert) {
 
for (Lead l: trigger.new) {

if (l.HubSpot_Campaign__c != null ) {
           CampaignMember cm = new CampaignMember();
                cm = new CampaignMember();
                cm.LeadId = l.Id;
                cm.CampaignId = l.HubSpot_Campaign__c; //You will have to know the ID or query for it or something
                cm.Status = 'Responded'; //Or whatever default status you want on the member
                
            insert cm;

}
}
}

 

This works perfectly fine but it generates an error if the lead record is updated because the lead will already exist in the campaign.

 

So what I need help on is to add a line which queries the campaignmembers and checks to see if the lead already exists for the campaignID listed in the custom field hubspot_campaign_c.

 

So what I was trying to do was create a list of campaign members where the leadID matches in the campaign member list but this is where I got stuck.  This will generate a list of campaigns the lead is in and I then need to filter it by campaignid = hubspot_campaign_c and then if campaignmember list is null add the campaign member.  

 

trigger LeadToCampaign on Lead (after update, after insert) {

List<Id> leads=new List<Id>();

for (Lead l: trigger.new) {

List<CampaignMember> cms=[Select LeadID, CampaignID FROM CampaignMember WHERE LeadID IN: leads];
        
if (l.HubSpot_Campaign__c != null) {
           CampaignMember cm = new CampaignMember();
                cm = new CampaignMember();
                cm.LeadId = l.Id;
                cm.CampaignId = l.HubSpot_Campaign__c; //You will have to know the ID or query for it or something
                cm.Status = 'Responded'; //Or whatever default status you want on the member
                
            insert cm;

}
}
}

 

Any help would be much appreciated.


Kev

Best Answer chosen by Admin (Salesforce Developers) 
Bhawani SharmaBhawani Sharma
This error shouldn't come. But still you can try with repalcing
insert cMembers;
to
database.insert( cMembers, false);

All Answers

Bhawani SharmaBhawani Sharma
You should create a map/set to hold the existing members.
Thsi can be something list this
trigger {

//Create a Set with LeadId - Campaign Id
for(CampignMamber cM: [Select data from CampaignMember where LeadId IN: Trigger.newMap.keySet()]) {

setVar(cM.LeadId + '-' + cM.CampaignId);

}

Now loop through the trigger new records and check if LeadId-CampignId already exists in set, do nothing elase create a new record
KevSnellKevSnell

I'm still struggling with this one.  

I understand the concept of creating a list of campaigns the Member is associated to but I need to filter this list to where the campaign id = hupspot_campaign field.  Then if the list is empty do the follow else do nothing.

Any further help would really be appreciated.


Thanks


Kevin

KevSnellKevSnell

Ok made a step forward by doing the below:

 

trigger LeadToCampaign on Lead (after update, after insert) {

List<Id> leads=new List<Id>();

for (Lead l: trigger.new) {

for(CampaignMember cm2 : [select LeadId, CampaignId from CampaignMember where LeadID IN: leads]) {
            if(cm2.campaignid == l.HubSpot_Campaign__c) {             
                break;                
            }
            
else if (l.HubSpot_Campaign__c != null) {
           CampaignMember cm = new CampaignMember();
                cm = new CampaignMember();
                cm.LeadId = l.Id;
                cm.CampaignId = l.HubSpot_Campaign__c; 
                cm.Status = 'Responded'; 
                
            insert cm;
}
}
}
}

 If someone could have look over and see if there is anything functionally wrong it would be really helpful.


Thanks

Kevin

Bhawani SharmaBhawani Sharma
By doing this way we will quickly fall in governor limit issue as your query in form loop.

I would suggest to re-read my earlier post. What all you need to do is, Create a set of all the existing leads with CampaignId. Set helps in maintain the uniquess.

Now when your are looping through your Trigger.New, fist check if that record already exist in Set. If yes, that means Lead is already a campaign member. elase you can create a new record
KevSnellKevSnell

Hi Bhawani,  thanks for your response.  I'm pretty new to this so still trying to learn.  I'll have a look and see if I can figure out what you're saying.

 

Kevin

Bhawani SharmaBhawani Sharma

Hi Kevin, I tried to comment as much as possible. Hopefully this will be helpful for you:

 

trigger LeadToCampaign on Lead (after update, after insert) {
	
	//Create a new set to hold all the Leads with CampaignId - Set will contain information in <LeadId - CampaignId> format
	Set<String> exsitingCampaignMembers = new Set<String>();

	//Query CampaignMember object and fetch all the members related to current context Leads
	for(CampaignMember cM : [Select LeadId, CampaignId from CampaignMember where LeadId IN: Trigger.newMap.keySet()]) {
		
		//Add in set
		exsitingCampaignMembers.add(cM.LeadId + '-' + cM.campaignId);
	}
	
	
	//Create a list to hold all the CampaignMember records to be inserted
	List<CampaignMember> cMembers = new List<CampaignMember>();

	//Loop through Trigger.New records and check if member need to be created
	for(Lead l : Trigger.New) {
		
		//Check if campaign is not null
		if (l.HubSpot_Campaign__c != null ) {
			
			//Create string to check the existing leads
			String uniquenessCriteria = l.Id + '-' + l.HubSpot_Campaign__c;
			
			//Check in set if this lead is already associated with any campaign record 
			//and only create the CampaignMember if Lead and Campaign is not found in set
			if(!exsitingCampaignMembers.contains(uniquenessCriteria))
				
				//Create a new Campign member record
				CampaignMember cm = new CampaignMember();
                cm = new CampaignMember();
                cm.LeadId = l.Id;
                cm.CampaignId = l.HubSpot_Campaign__c;
                cm.Status = 'Responded';

				//Add this record in the list of Campaign Members to be inserted
				cMembers.add(cm);
            }
		}
	}

	//Insert records in database
	if(cMembers.size() > 0)
		insert cMembers;
}

 

KevSnellKevSnell

I seem to be getting the error with this:

 

setVar(cM2.LeadId + '-' + cM2.CampaignId);

 

KevSnellKevSnell

Awesome thankyou.  I'll have a look now and see if it makes sense.

Bhawani SharmaBhawani Sharma
Did you try the latest code?
KevSnellKevSnell

Just tried it now and get the error from this line of code:

 

    //Insert records in database
    if(cMembers.size() > 0)
        insert cMembers;

 

 

Error: Compile Error: unexpected token: if at line 44 column 4

KevSnellKevSnell

Ok fixs this as it was just in the wrong position but now i get the error from cm = new CampaignMember(); in this line of code:

 

                //Create a new Campign member record
                CampaignMember cm = new CampaignMember();
                cm = new CampaignMember();
                cm.LeadId = l.Id;
                cm.CampaignId = l.HubSpot_Campaign__c;
                cm.Status = 'Responded';

                //Add this record in the list of Campaign Members to be inserted
                cMembers.add(cm);

 Sorry should say error is: 

Variable does not exist: cm at line 32 column 17

 

KevSnellKevSnell

I tweaked the code as there was a { missing after an if statement:

 

trigger LeadToCampaign on Lead (after update, after insert) {
    
    //Create a new set to hold all the Leads with CampaignId - Set will contain information in <LeadId - CampaignId> format
    Set<String> existingCampaignMembers = new Set<String>();

    //Query CampaignMember object and fetch all the members related to current context Leads
    for(CampaignMember cM : [Select LeadId, CampaignId from CampaignMember where LeadId IN: Trigger.newMap.keySet()]) {
        
        //Add in set
        existingCampaignMembers.add(cM.LeadId + '-' + cM.campaignId);
    }
    
    
    //Create a list to hold all the CampaignMember records to be inserted
    List<CampaignMember> cMembers = new List<CampaignMember>();

    //Loop through Trigger.New records and check if member need to be created
    for(Lead l : Trigger.New) {
        
        //Check if campaign is not null
        if (l.HubSpot_Campaign__c != null ) {
            
            //Create string to check the existing leads
            String uniquenessCriteria = l.Id + '-' + l.HubSpot_Campaign__c;
            
            //Check in set if this lead is already associated with any campaign record 
            //and only create the CampaignMember if Lead and Campaign is not found in set
            if(!existingCampaignMembers.contains(uniquenessCriteria)){
                
                //Create a new Campign member record
                CampaignMember cm = new CampaignMember();
                cm = new CampaignMember();
                cm.LeadId = l.Id;
                cm.CampaignId = l.HubSpot_Campaign__c;
                cm.Status = 'Responded';

                //Add this record in the list of Campaign Members to be inserted
                cMembers.add(cm);
            }
        }
        
       }
   
   //Insert records in database
    if(cMembers.size() > 0)
        insert cMembers;
        
    }

 While it saves if I try to add the campaignid to l.hubspot_campaign to a lead who is already in the campaign I get the following error:

 

Error:Apex trigger LeadToCampaign caused an unexpected exception, contact your administrator: LeadToCampaign: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, This entity is already a member of this campaign: []: Trigger.LeadToCampaign: line 46, column 1

Bhawani SharmaBhawani Sharma
This error shouldn't come. But still you can try with repalcing
insert cMembers;
to
database.insert( cMembers, false);
This was selected as the best answer
KevSnellKevSnell

Excellent that fixed the issue!

 

Here's the full code for anyone else:

 

trigger LeadToCampaign on Lead (after update, after insert) {
    
    //Create a new set to hold all the Leads with CampaignId - Set will contain information in <LeadId - CampaignId> format
    Set<String> existingCampaignMembers = new Set<String>();

    //Query CampaignMember object and fetch all the members related to current context Leads
    for(CampaignMember cM : [Select LeadId, CampaignId from CampaignMember where LeadId IN: Trigger.newMap.keySet()]) {
        
        //Add in set
        existingCampaignMembers.add(cM.LeadId + '-' + cM.campaignId);
    }
    
    
    //Create a list to hold all the CampaignMember records to be inserted
    List<CampaignMember> cMembers = new List<CampaignMember>();

    //Loop through Trigger.New records and check if member need to be created
    for(Lead l : Trigger.New) {
        
        //Check if campaign is not null
        if (l.HubSpot_Campaign__c != null ) {
            
            //Create string to check the existing leads
            String uniquenessCriteria = l.Id + '-' + l.HubSpot_Campaign__c;
            
            //Check in set if this lead is already associated with any campaign record 
            //and only create the CampaignMember if Lead and Campaign is not found in set
            if(!existingCampaignMembers.contains(uniquenessCriteria)){
                
                //Create a new Campign member record
                CampaignMember cm = new CampaignMember();
                cm = new CampaignMember();
                cm.LeadId = l.Id;
                cm.CampaignId = l.HubSpot_Campaign__c;
                cm.Status = 'Responded';

                //Add this record in the list of Campaign Members to be inserted
                cMembers.add(cm);
            }
        }
        
   //Insert records in database
    if(cMembers.size() > 0)
        database.insert( cMembers, false);
      }  
    }

 

KevSnellKevSnell

Bhawani - thank you for your help and description! Has really helped with understanding how to generate lists and use them effectively.  I marked your last post as the accepted solution to show your help and gave you some kudos!

bzbz
I was struggling with trying to match on multiple keys (LeadId and Campaign from CampaignMember).  The concatenation solution "cM.LeadId + '-' + cM.campaignId" into the Set was what I was missing.  Great solution and Much Thanks!!!