1

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...

  • 1
    Can you complete the end of the error please? "Required fields are missing: [Co..." – Cloud Ninja Apr 3 '14 at 10:38
  • 1
    Check all the required fields for OpportunityContactRole in your org – highfive Apr 3 '14 at 10:39
  • @brovasi, sadly it does not show anything more, that is the end of the error message. – Carl S Apr 3 '14 at 10:41
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;
}
  • thanks that seemed to work! Only thing I have noticed is that it doesn't set that contact as the Primary contact, just as a contact. – Carl S Apr 3 '14 at 11:07
  • 1
    try with role.isPrimary = true. – Cloud Ninja Apr 3 '14 at 11:08
  • I just noticed that everytime you edit and save the quote, it re-adds the contact as another contact. Just ended up with the same contact on a quote several times! – Carl S Apr 3 '14 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.