[SalesForce] Opportunity Contact Role is required to create an opportunity

When creating an opportunity as of now opportunity contactrole is not mandatory.System should display error message "Opportunity Contact Role" is required to create an opportunity if system did not find up the "opportunity contact role" upon creation of the opportunity.You can use triggers and utility class

Best Answer

Opportunity Contact Roles (OCR) by definition cannot be created prior to the opportunity existing.

Thus, when a user saves a new opportunity, there will never be a related OCR.

You could do this if you wanted to prevent opportunity updates without a related OCR:

  1. Create a read-only integer field on your opportunity
  2. Create a before-update trigger on the opportunity that populates this field with a count of related OCRs
  3. Create a validation rule that prevents saving an opportunity when the number field is not greater than 0.

Pseudo code for trigger:

 trigger updateCount on Opportunity (before update) {
    map <id, list<opportunityContactRole>> myMap = new map <id, list<opportunityContactRole>> ();
    for (opportunitycontactrole OCR: [SELECT id, opportunityid, contactid, role from opportunityContactRole WHERE opportunityid in :trigger.old]) {
        if (myMap.containsKey(OCR.opportunityid)) {
            myMap.get(OCR.opportunityid).add(OCR);
        } else {
            myMap.put(OCR.opportunityid, new list <opportunitycontactrole> {OCR});
        }
    }
    list <opportunity> oppsToUpdate = new list <opportunity> ();
    for (opportunity oppID: myMap.keySet()) {
        oppsToUpdate.add( new opportunity(id=oppID, OCRcount=myMap.get(oppID).size()))
    }
    update oppsToUpdate;
}
Related Topic