Search code examples
triggerssalesforceapex-code

Salesforce.com Trigger- Require primary contact to save opportunity


There are currently two AppExchange apps that do this, but I was wondering if anyone has figured out how to do this without installing an app, as the number of apps I can install in my organization is limited.

The trigger needs to check to see if there is a contact listed, if not, then an error message should display. I tried this with validation rules, but had no luck because the OpportunityContactRole is a separate object.

Could someone provide their thoughts?


Solution

  • trigger OpportunityBeforUpdate on Opportunity (before update) {
       set<Id> oppIdSet = new set<Id>();
       set<Id> OpportunityContactRoleIdSet = new set<Id>();
       for(Opportunity opp:trigger.new){
      if("Some condition")oppIdSet.add(opp.Id);
       }
     for(OpportunityContactRole ocr:[select Id,OpportunityId from OpportunityContactRole                                        where OpportunityId in:oppIdSet]){
    OpportunityContactRoleIdSet.add(ocr.OpportunityId);
       }
      for(Opportunity opp:trigger.new){
    if(oppIdSet.contains(opp.Id) && !OpportunityContactRoleIdSet.contains(opp.Id))
        opp.addError('Some error'); 
      }
    

    }