Search code examples
triggerssalesforceapex-code

opportunitycontactrole in salesforce triggers


I'm working on an apex trigger and I keep getting errors in selecting 'contact' I've tried a lot of different configurations of this sort of code and i just can't get it to work. the forceide says there is no contact on opportunitycontactrole i'm out of ideas.

Here is my code so far:

trigger add_primary_advisor on Opportunity(after insert, after update) { List primaries=new List();

 for(Opportunity o:
    [Select Contact
    From OpportunityContactRole
    Where OpportunityContactRole='Staff' and isPrimary='True']) {

    primaries.add(Contact);
    }
    return primaries;

}

Solution

  • Contact is not a valid field on OpportunityContactRole

    This Object stores only the reference to Contact as ContactId.

    If you want to access Contact's fields from OpportunityContactRole you can access by cross-refrencing to its fields as as below.

    List<Contact> primaries = new List<Contact>();
    for(Opportunity o:
        [Select Contact.FirstName, Contact.LastName, Contact.Email
         From OpportunityContactRole
         Where OpportunityContactRole='Staff' and isPrimary='True']) {
       primaries.add(new Contact(FirstName=o.Contact.FristName, 
                LastName = o.Contact.LastName, Email =o.Contact.Email));
    }