Find your content:

Search form

You are here

Auto Add Quote Contact as Primary Opportunity Contact

 
Share

I am trying to create an apex trigger that automatically adds the Quote Contact as the Primary Opportunity Contact. I am using the code below

trigger OpportunityContactRoleTrigger on Quote (after insert, after update) {
    List<OpportunityContactRole> roles = new List<OpportunityContactRole>();
    for (Quote q : [SELECT Id, Contact.Id, OpportunityId FROM Quote WHERE Id =: Trigger.new AND OpportunityId != null]) {
        OpportunityContactRole role = new OpportunityContactRole();
        role.ContactId = q.Contact.Id;
        role.OpportunityId = q.OpportunityId;
        role.Role = 'Other';
        roles.add(role);
    }
    insert roles;
} 

However, when I try to publish this to the active instance I get the following error:

LeapfrogQuoteController.test_invoke() Class 110 1 Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, OpportunityContactRoleTrigger: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Co...


Attribution to: Carl S

Possible Suggestion/Solution #1

Be sure your Quote has a ContactId. I think that's your problem your Contact is null.

trigger OpportunityContactRoleTrigger on Quote (after insert, after update) {
    List<OpportunityContactRole> roles = new List<OpportunityContactRole>();
    for (Quote q : [SELECT Id, ContactId, OpportunityId FROM Quote WHERE Id =: Trigger.new AND OpportunityId != null 
AND ContactId != null]) {
        OpportunityContactRole role = new OpportunityContactRole();
        role.ContactId = q.ContactId;
        role.OpportunityId = q.OpportunityId;
        role.Role = 'Other';
        roles.add(role);
    }
    insert roles;
}

Attribution to: Cloud Ninja
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/31738

My Block Status

My Block Content