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
franklin_atxfranklin_atx 

Update a lookup field within the same object

Would like to know if you can create a apex trigger that will populate a lookup field against the LEAD object from the Campaign Member table field "LEAD".

 

I found that LEAD is on the Campaign Member but I'm unable to use a formula field against "LEAD" to pull in LEAD information back to the Campagin Member table. Therefore, I created a Lookup Field that links me back to the LEAD table and then created the formula fields that provide the data. 

 

Now, I just need to auto update the new LEAD lookup field with the current Campaign Member Lead ID so my formula fields will work. 

 

Any thoughts on this?

Thanks,

Best Answer chosen by Admin (Salesforce Developers) 
jkucerajkucera

Yes - you can do this.  Syntax is something like this assuming your custom field is called LeadID__c:

 

trigger populateLead on CampaignMember(before insert){ for (CampaignMember cm:Trigger.new){ if(cm.ContactID==Null){ cm.LeadID__c=cm.LeadID; } } }

 

 

Note that we recognize this is a gap and is very high on our roadmap to fix (~6 months safe harbor)

All Answers

jkucerajkucera

Yes - you can do this.  Syntax is something like this assuming your custom field is called LeadID__c:

 

trigger populateLead on CampaignMember(before insert){ for (CampaignMember cm:Trigger.new){ if(cm.ContactID==Null){ cm.LeadID__c=cm.LeadID; } } }

 

 

Note that we recognize this is a gap and is very high on our roadmap to fix (~6 months safe harbor)

This was selected as the best answer
franklin_atxfranklin_atx

John,

Thanks and I've modified it a bit to our instance/fields:

 

trigger CMLeadData on CampaignMember (before insert) {
for (CampaignMember cm:Trigger.new){
        if(cm.ContactID==Null)
            cm.Lead_Name__c=cm.LeadID;
                where cm.CreatedDate = TODAY
            }
    }

 

However, the line I added,  where cm.CreatedDate = TODAY fails. Is there syntex that will work to trigger only if CM is created today? The reason for this is we run reports based on CM Last Modified date so without logic (we believe) in the Apex to only trigger on "Today" we beleive the APEX will trigger and update the entire db which wouldn't be good for our reporting. 

jkucerajkucera

No need for the "today" line as the trigger will only update campaign members as they are created.  "Before Insert" means that this code executes when any new campaign member is created, at the time the record is created.

 

The trigger won't affect any existing members - only triggers with "before update" or "after update" could update existing members.

franklin_atxfranklin_atx
That was right in front of me. Thanks!