+ Start a Discussion

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

Hi Vivek
Apex Trigger -->
trigger DeleteCon on Account (before update) {
    if(Trigger.isupdate && Trigger.isbefore){

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(accId.size() > 0){
            conList = [Select Id from Contact where Account__Id IN : accId];
            try {
                if(conList.size() > 0){
                    delete conList;
            }catch(DMLException e){

if you found this answer helpful then please mark it as best answer so it can help others.      
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) {
		//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) {
					delete lstContact;
				} catch(DMLException dmlEx){
					system.debug('----DMLException-----' + dmlEx);

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

Thanks Niraj