APEX – Don’t Allow Contact Deletion if Contact is an Opportunity Contact Role.

This is not CPQ but a short, quick, request from someone for some code. The request is: If a Contact is an Opportunity Contact Role of same Account, don’t allow deleting it. Below is the code. I didn’t think “of same Account” matters, so I didn’t write that into the code.

APEX Trigger – ContactTriggers

trigger ContactTriggers on Contact (before delete) {
ContactTriggerHelper.helpTrigger();
}

APEX Class – ContactTriggerHelper

public class ContactTriggerHelper {
    public class ContactException extends Exception {}
    public static void helpTrigger() {
        // if is before,
        if (trigger.isBefore) {
             // if is delete,
             if (trigger.isDelete) {
                 // query contact roles for these contact ids.
                 List<OpportunityContactRole> crList = [select id from OpportunityContactRole where ContactId in :trigger.oldMap.keySet()];
                 // if contact roles list is not empty,
                 if (crList.size() > 0) {
                     // throw error.
                     throw new ContactException('Unable to delete Contact.  This Contact is listed as a Contact Role on an Opportunity.');
                 }
            }
        }
    }
}

2 thoughts on “APEX – Don’t Allow Contact Deletion if Contact is an Opportunity Contact Role.

  1. if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API. if this trigger was fired after a record is recovered from the Recycle Bin. This recovery can occur after an undelete operation from the Salesforce user interface, Apex, or the API.

    1. I am not sure what you’re saying. But I think you’re saying this code does not address the undelete operation. This code is designed to prevent the deletion of a Contact. This should not fire for undelete.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.