1

I created a custom lookup field in my Account object named Campaign__c. I am trying to map the standard Campaign field from the Lead object to this one. But I am getting this error Invalid field CampaignId for SObject Lead in my trigger. Meanwhile, here's my trigger:

updateField

trigger UpdateField on Lead (after insert, after update) {
    List<Account> accsToUpdate = new List<Account>();
    for(Lead lead1 : Trigger.New){
        Account tempAcc = new Account(Id = lead1.ConvertedAccountId);
        if(tempAcc.Campaign__c != lead1.CampaignId){
            tempAcc.Campaign__c = lead1.CampaignId;
            accsToUpdate.add(tempAcc);            
        }
    }
    update accsToUpdate;
}
1
  • In the schema level, there is no field named CampaignId in Lead object. Here's an article about it. Also link to @cropredy's answer which helps you to understand what happens behind the scene.
    – Praveen
    Commented Jul 24, 2016 at 9:46

1 Answer 1

2

Campaign field in Lead is not accessible through SOQL. For this you need to do use CampaignMember.

    trigger UpdateField on Lead (after insert, after update) 
    {
        Map<ID, ID> CampaignIDs= new Map<ID, ID>();
        List<Account> accsToUpdate = new List<Account>(); 

        List<CampaignMember> cms = [SELECT CampaignID, LeadID, Status FROM CampaignMember WHERE LeadID in : Trigger.new]; 

        for(CampaignMember cm:cms)
        { 
            if(!CampaignIDs.containsKey(cm.LeadID))
            { 
                CampaignIDs.put(cm.LeadID, cm.CampaignID); 
            }
        }

        for(Lead lead1 : Trigger.New)
        {
            Account tempAcc = new Account(Id = lead1.ConvertedAccountId);
            if(tempAcc.Campaign__c != CampaignIDs.get(lead1.Id)){
                tempAcc.Campaign__c = CampaignIDs.get(lead1.Id);
                accsToUpdate.add(tempAcc);            
            }
        }
        update accsToUpdate;
   }

Hope it helps you :)

1
  • glad it works for you :). @Praveen: links suggested by you are very useful. Commented Jul 24, 2016 at 10:55

You must log in to answer this question.

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