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());
}
}
}