0

I created a trigger to add the recent campaign to the contact record. An error now occurs when adding a lead to a record.

Error when adding lead to campaign: UpdateContact: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.UpdateContact: line 23, column 1

Trigger code on Campaign Member:

trigger UpdateContact on CampaignMember (before insert)

{

    set<id>contactids=new set<id>();

    contact cont;

    for(campaignmember cam:trigger.new)

    {

    

      contactids.add(cam.ContactId);  

        

    }

//Map<id, contact> contacts = new map<id, contact>([select id,Description,createddate,name from contact where id in:contactids ORDER BY CreatedDate DESC limit 1]);

Map<id, contact> contacts = new map<id, contact>([select id,First_Campaign__c,Description,createddate,name from contact where id in:contactids]);

    

    //Map<Id,Campaignmember>stat=new Map<Id,Campaignmember>([select id,contactid,campaignid from Campaignmember where contactid in:contactids]); 

    

//Map<id, contact> contact1 = new map<id, contact>([select id,Description,createddate,name from contact where id in:contactids order by createddate desc limit 1]);    

 

    for(Campaignmember bolly:trigger.new)

    {

        

       contact cont=contacts.get(bolly.ContactId);

       if(cont.First_Campaign__c==null)

       {

       cont.First_Campaign__c=bolly.CampaignId;

       update cont; 

       }

    }

    

Map<id,contact> contact1 = new map<id,contact>([select id,name from contact where id in:contactids]);    

     

    for(Campaignmember bolly1:trigger.new)

    {

        

       contact contra=contact1.get(bolly1.ContactId);

       

       contra.Most_Recent_Campaign__c=bolly1.CampaignId;

   

       update contra; 

       }

        

    }

1 Answer 1

2

In this part of your code:

contact cont=contacts.get(bolly.ContactId);

if(cont.First_Campaign__c==null)

If bolly.ContactId is null, then cont will be null, which means you will get an error when you try to access cont.First_Campaign__c.

You will need to add a check whether cont is null or not.

E.g.

Contact cont = contacts.get(bolly.ContactId);
if(cont != null){
    if(cont.First_Campaign__c == null){
        cont.First_Campaign__c = bolly.CampaignId;
        update cont; 
    }
}

By the way, it is not advised to perform DML operations inside for-loops as there is a risk you may hit Salesforce limits. See here for more details: Bulk Apex Triggers

3
  • How do I check whether cont is null? if(cont==null)
    – Andi
    Commented Mar 8 at 20:34
  • yes, but in your case you'll need if(cont != null)
    – fred
    Commented Mar 9 at 1:26
  • I have updated my answer with a code example
    – fred
    Commented Mar 9 at 1:32

You must log in to answer this question.

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