1

I am writing an Apex Trigger that will take the Primary_Contact__c from an Opportunity that has been Closed Won and the Amount != Null and add that Contact to a Campaign called Closed Won.

Primary_Contact__c is a Lookup field to the Contact object and has a relationship name of Primary_Contact__r.

Below is the code that I currently have. It is not throwing any errors it is just not adding the Contact to the proper Campaign upon saving of the record.

trigger UpdateClosedWonMembers on Opportunity (before update) {
List<CampaignMember> members = new List<CampaignMember>();

for (Opportunity opp : Trigger.new) {
    if (opp.StageName == 'Closed Won' && opp.Amount != Null) {
        CampaignMember cm = new CampaignMember(CampaignId = '7011a000000BBny', ContactId = opp.Primary_Contact__r.Id, Status = 'Sent');

        members.add(cm);
    }

    try{
        insert members;
    } catch(DmlException e) {
        System.debug('An unexpected error has occured: ' + e.getMessage());
    }
}
}
2
  • @Ratan Please re-read the question. I stated that it is not throwing any errors. It is simply just not working.
    – cmmoutes13
    Commented Aug 3, 2016 at 15:06
  • In triggers, you won't have the values of Relationship fields. So opp.Primary_Contact__r.Id will be null. Use opp.Primary_Contact__c Commented Aug 3, 2016 at 15:08

1 Answer 1

4

The reason for the error has to do with context:

CampaignMember cm = new CampaignMember(CampaignId = '7011a000000BBny',
                      ContactId = opp.Primary_Contact__r.Id, Status = 'Sent');

When the trigger executes the values of lookup fields are not available in Trigger.new. If you need Lookup fields (or children) you have to SOQL query them

opp.Primary_Contact__r.Id

Instead, change the line to

CampaignMember cm = new CampaignMember(CampaignId = '7011a000000BBny',
                      ContactId = opp.Primary_Contact__c, Status = 'Sent');

As an aside -- never use hard coded ids as they cause all sorts of deployment issues. Instead, query for the CampaignId

3
  • 1
    Thanks! This works! Also thanks to @Vigneshwaran because he commented the same idea.
    – cmmoutes13
    Commented Aug 3, 2016 at 15:13
  • Also I was planning on changing the hard code ID, just put it there for now to make sure this would work. I will change before deployment.
    – cmmoutes13
    Commented Aug 3, 2016 at 15:14
  • @cmmoutes13 --good, Community tends to knee jerk (me included) when they see hard-coded IDs as they are really bad practice :-) the after update idea is also meritorious.
    – cropredy
    Commented Aug 3, 2016 at 15:16

You must log in to answer this question.

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