0

trying to write a simple trigger for populating a couple of custom lookup fields on Contacts. We have 2 custom fields called "First Campaign" and "Most Recent Campaign". I'm trying to get "First Campaign" populated with the first campaign the Contact was added to and "Most Recent Campaign" with the latest campaign they've been added to. Here's what I have so far, would love any help with this. Thanks in advance!

trigger FirstAndMostRecentCampaignOnContact on Contact (after insert, after update) {

Set<Id> CampaignIds = new Set<Id>();
for(Contact CON: Trigger.new) CampaignIds.add (CON.MostRecentCampaign__c);
List<Campaign> c= new List<Campaign>([
    select 
    Id
    from Campaign 
    where Id = :CampaignIds ORDER BY CreatedDate DESC NULLS LAST LIMIT 1
]);
Map<Id, List<Campaign>> cmMap = new Map<Id, List<Campaign>>();
for (Campaign cm: c) {
    if (cmMap.containsKey(cm.Id)) {
        List<Campaign> x;
        x = cmMap.get(cm.Id);
        x.add(cm);
        cmMap.put(cm.Id, x);
    } else {
        List<Campaign> tmp = new List<Campaign>();
        tmp.add(cm);
        cmMap.put(cm.Id, tmp);
    }
}
List<Contact> CON1 = new List<Contact>(); 
for(Contact newCon: Trigger.new){
    if (cmMap.containsKey(newCon.MostRecentCampaign__c)) {
        for (Campaign cm: cmMap.get(newCon.MostRecentCampaign__c)) {
            CON1.add(
                New Contact(
                    id=newCon.id)                    
            );
        }
    }
}
} 
1
  • Hi Patrick, what's the issue you are working on with this code? Can you edit your question to show a specific problem you could use help with?
    – David Reed
    Commented Jan 18, 2019 at 23:13

1 Answer 1

1

You should consider a trigger on the Campaign Member object rather than the Contact. Changes to Contact would not result in changing the First or Most Recent Campaign.

When a new Campaign Member record is created, determine if it points to a Contact (as opposed to a lead), and if so, determine if it's the first Campaign for the Contact; it's probably a given that it will be the Most Recent.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .