function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
louisa barrett 7louisa barrett 7 

Remove contact from related cases and service contracts before delete

Hi,

We use cases and service contracts and as SF prevent a contact being deleted that is associated to one of these records, when we want to delete a contact that is associated to a case or service contract each of these records needs to be individually updated to remove the contact.
I was hoping to remove the contact from these records on a before delete trigger on the contact. This is failing though as I think the SF code that is checking if the contact belongs to any cases or service contracts is rolling back my updates in my before trigger.
Does anyone know if this is possible thorugh a trigger?
I don't really want to launch a flow to delete the relationships on an individual contact record as I would like to be able to mass delete contacts.
This is the method that is called from the contact trigger on a beforeDelete
private static void removeContactFromRelatedObjects(Map<Id, Contact> oldContactsMap)
    {
        List<Contact> myContacts = new List<Contact>([SELECT ID, (SELECT Id, CaseNumber FROM Cases), (SELECT ID, ContractNumber FROM ServiceContracts) 
                                                            FROM Contact 
                                                            WHERE Id in : oldContactsMap.keyset()]);
        List<ServiceContract> mySCs = new List<ServiceContract>();
        List<Case> myCases = new List<Case>();
        for(Contact c : myContacts)
        {
            mySCs.addAll(c.ServiceContracts);
            myCases.addAll(c.Cases);
        }
        for(ServiceContract sc : mySCs)
        {
            sc.Contact = null;
        }
        for(Case c : myCases)
        {
            c.Contact = null;
        }
        database.update(mySCs, false);
        database.update(myCases, false);
    }
Many thanks for any help