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
Lokesh Rayapati4Lokesh Rayapati4 

By using triggers add lead to campaign abc record if the lead status is ' Open-Not Contacted ', and also remove campaign abc if the status in lead status is changed from 'Open- Not Contacted' to something else

Hi,
 
I'm struggling to complete this trigger.If the lead status is ' Open-Not Contacted ' then the record should be added to campaign record (Create one Record Name- abc) and also if the status is changed from ' Open-Not Contacted ' to something else then the record (abc) in campaign should be removed.

I firstly tried to created junction object  by adding 2 master detail that is Lead and campaign but, When creating relationship Lead is not appearing to select. My idea is that we can do this with campaign member object. please help me in solving this trigger which involves
relationship.

Thanks in advance.
 
Best Answer chosen by Lokesh Rayapati4
CharuDuttCharuDutt
Hii Lokesh Rayapati
Try Below Trigger
Make Lead Lookup Field On Campaign  =  Lead__c
trigger dfsdhbfjsdbvj on Lead (after insert,after update){
    set<Id> lstId = new set<id>();
    list<Campaign> lstCampaign = new list<Campaign>();
    if(trigger.IsInsert){
        for(Lead l : trigger.new){
            if(l.Status == 'Open - Not Contacted'){
                Campaign c= new Campaign();
                c.Name = 'Test' + l.FirstName+''+l.LastName;
                c.Lead__c = l.Id;
                lstCampaign.add(c);
            }
        }
    }
    if(trigger.IsAfter && trigger.IsUpdate){
        for(lead l :trigger.new){
            if(l.Status != Trigger.oldMap.get(l.Id).Status && l.Status != 'Open - Not Contacted'){
                lstId.add(l.Id);
            }else if(l.Status != Trigger.oldMap.get(l.Id).Status && l.Status == 'Open - Not Contacted'){
                Campaign c= new Campaign();
                c.Name = 'Test' + l.FirstName+''+l.LastName;
                c.Lead__c = l.Id;
                
                lstCampaign.add(c);
            }  
        }
    }
    list<Campaign> lstCampaignToDelete = [Select Id,Lead__c From Campaign Where lead__c IN: lstId];
    if(lstCampaignToDelete.size()>0){
        Delete lstCampaignToDelete;
    }
    if(lstCampaign.size()>0){
        insert lstCampaign;
    }
}
Please Mark It As Best Answer If It Helps
Thank You!