Requirement: Prevent to delete contact record when account deleted as Cascade delete.
Implementation:
Using apex trigger, In before delete, set deleted account's associated contact records AccountId field to null..
Refer below apex trigger code :
trigger accountTrigger on Account (before delete){
List<Contact> conToUpdateList = new List<Contact>();
Set<Id> accountIdSet = new Set<Id>();
for(Account acc : trigger.old){
accountIdSet.add(acc.Id);
}
if(!accountIdSet.isEmpty()){
List<Contact> contactList = [SELECT id
FROM Contact
WHERE AccountId In: accountIdSet];
for(Contact con : contactList){
con.AccountId = null;
conToUpdateList.add(con);
}
if(!conToUpdateList.isEmpty()){
update conToUpdateList;
}
}
}
No comments:
Post a Comment