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
Atul Shendge 2Atul Shendge 2 

Write a trigger to delete the contacts associated with account object where account is inactive.

Hi All,
Write a trigger to delete the contacts associated with account object where account is inactive.

Regards,
Atul
Best Answer chosen by Atul Shendge 2
AnudeepAnudeep (Salesforce Developers) 
Hi Atul, 

Unsure when do you want the trigger to fire but here is a sample code 
trigger DeleteRelatedContact on Account (before update)  
{  
    List<Account> accList = new List<Account>();  
    Set<id> accIdSet = new Set<id>();  
    for(Account acc : Trigger.new)  
    {  
        if(acc.isActive=false) {
            accIdSet.add(acc.id);  
        }
    }  
 
 List<Contact> conList = new List<Contact>([Select lastname,id,accountid From Contact Where Accountid IN : accIdSet]); 
 if(conList.size()>0) {
    delete conList;
 }


Anudeep

All Answers

ANUTEJANUTEJ (Salesforce Developers) 
Hi Atul,

Have you considered the OOB tools like flows for your scenario??

Regards,
Anutej
AnudeepAnudeep (Salesforce Developers) 
Hi Atul, 

Unsure when do you want the trigger to fire but here is a sample code 
trigger DeleteRelatedContact on Account (before update)  
{  
    List<Account> accList = new List<Account>();  
    Set<id> accIdSet = new Set<id>();  
    for(Account acc : Trigger.new)  
    {  
        if(acc.isActive=false) {
            accIdSet.add(acc.id);  
        }
    }  
 
 List<Contact> conList = new List<Contact>([Select lastname,id,accountid From Contact Where Accountid IN : accIdSet]); 
 if(conList.size()>0) {
    delete conList;
 }


Anudeep
This was selected as the best answer
Debabrata Sahu 1Debabrata Sahu 1
Create a flow for delete record and connect it with a process builder(assign account active status in it) . Other option