+ Start a Discussion
vicky30vicky30 

Apex trigger to delete contacts when account is changed

Hi Friends,
I have one custom object called "call" and this object is child to account object.
When we click on new button on call object, it will redirect to VF page, In that page we have Account lookup field, and we have section called Attendee(Contact user), The attendee are related to that account.
My requirement is when we update the account with different account name, Then the old account related attendee should be delete.   
I want the trigger logic. Could any please help me on this.
Please find the screenshot for reference.


Thanks in Advance,
vivekUser-added image
 
Akshay_DhimanAkshay_Dhiman

Hi Vivek
 
Apex Trigger -->
trigger DeleteCon on Account (before update) {
    if(Trigger.isupdate && Trigger.isbefore){
        HelpAccountTrig.conDelete(Trigger.New,Trigger.newMap);      
    }
}

Apex Helper classs
public class HelpAccountTrig {
    public static void conDelete(List<Account> accList, map<Id,Account> accMap){
        List<Contact> conList = new List<Contact>();
        Set<Id> accId = new Set<Id>();
        for(Account a :accList){
            if(a.Name!=accMap(a.Id).Name){
                accId.add(a.Id);
            }
        }
        if(accId.size() > 0){
            conList = [Select Id from Contact where Account__Id IN : accId];
            
            try {
                if(conList.size() > 0){
                    delete conList;
                }                
                System.debug(conList);
            }catch(DMLException e){
                System.debug('Error'+e.getMessage());
            }
        }
    }
}


if you found this answer helpful then please mark it as best answer so it can help others.      
  
  Thanks 
  Akshay
  
Niraj Kr SinghNiraj Kr Singh
Hi Vivek,

Considering your requirements:
Like While updating your existing account with different Name, then related contacts should be deleted.
Note: "Attendee" considering as "Contact". If it is other object change the Object API name in SELECT statement(in SOQL present in below code).
trigger AccountAttendeeTrigger on Call__c (after update) {
	Set<Id> accountIdsSet = new Set<Id>();
	
	if(Trigger.isAfter && Trigger.isUpdate) {
		//To get accountIds related to all changed name.
		for(Call__c objCall : Trigger.old) {
			if(objCall.Account__c.Name != Trigger.newMap.get(objCall.Id).Account__c.Name) {
				accountIdsSet.add(objCall.Id);
			}
		}
		//To delete all contacts related to un-matched name of accounts
		if(!accountIdsSet.isEmpty()) {
			List<Contact> lstContact = [SELECT Id, Name FROM Contact WHERE AccountId IN: accountIdsSet];
			if(lstContact != null) {
				try{
					delete lstContact;
				} catch(DMLException dmlEx){
					system.debug('----DMLException-----' + dmlEx);
				}
			}
		}
	}
}

If it helps you, Mark it your answer to help others.

Thanks
Niraj
vicky30vicky30
Thanks Niraj