function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
tania chattopadhyaytania chattopadhyay 

Hi all, I need an urgent help. I want to tag a campaign where a particular lead is already there in campaign member , with a custom campaign lookup field in lead object.

I have written an apex trigger:

trigger CampaignFacebook on Lead (before insert) {
    for(Lead l : Trigger.new)
    {
       System.debug('****---'+l.id); 
        
      for(CampaignMember c:[Select CampaignId from CampaignMember where LeadId =:l.id])
      {
       
           System.debug('######---'+c.CampaignId);
           l.Campaign_Details_Manual_NEW__c=c.CampaignId;
       }    
           
    }
    
    
}


For example-
Camapign name: campaign A
Lead name- lead A
campaign lookup Field name in Lead-  Campaign_Details_Manual_NEW__c

Under Campaign A, lead A is already there in Campaign Member, now need to tag Campaign A in Campaign_Details_Manual_NEW__c field in lead object.


Plz help me,I have written this in Sandbox.
 
Akshay_DhimanAkshay_Dhiman
Hi Tania,

 try this code
 
trigger CampaignFacebook on Lead (after insert) {
 Set<Id> lId = new Set<Id>();
    for(Lead l : Trigger.new)
    {
  lId.add(l.Id);
        System.debug('****---'+l.id); 
 }
      List<CampaignMember> campMemList:[Select CampaignId from CampaignMember where LeadId IN:lId];
   
   for(Lead l : Trigger.new){
    for(CampaignMember c:campMemList){
     if(c.LeadId==l.Id){
    Lead newLead = new Lead();
    newLead.id=l.id;
    newLead.Campaign_Details_Manual_NEW__c=c.CampaignId;
    updateLead.add(newLead)
     }
     
    }
   }
   
   if(updateLead.size() > 0){
    update updateLead;
   }
  
    
}



if you found this answer helpful then please mark it as best answer so it can help others.

Thanks,
 Akshay
tania chattopadhyaytania chattopadhyay
This code is not working.This is not the right way to query .Errors are comning.Please help me in solving this.