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
Joan RubioJoan Rubio 

Trigger to prevent Account deletions

I'm new programming and need some help...
I want to make a trigger to prevent deleting Accounts that have any Location associated. If an account has an associated Location, I want to display an error message.
There are a lookup field on Accounts to Location (Location__c).
Can you help me?
Thanks!
Best Answer chosen by Joan Rubio
Anupama SamantroyAnupama Samantroy
Hi Joan,
trigger AccountTrigger on Account(before delete){
for(Account acc: trigger.old){
if(acc.Location__c !=null){
acc.addError('Account is associated with location. Cannot be deleted');
}
}

}


Thanks
Anupama

All Answers

Anupama SamantroyAnupama Samantroy
Hi Joan,
trigger AccountTrigger on Account(before delete){
for(Account acc: trigger.old){
if(acc.Location__c !=null){
acc.addError('Account is associated with location. Cannot be deleted');
}
}

}


Thanks
Anupama
This was selected as the best answer
Agus NovakAgus Novak
all that you have to do in the trigger before delete is something like the following:
 
trigger deleteAccount on account (before delete) {
    	list<account> toDelete = new list<account>();
            for (account aux : Trigger.new){
    			if(aux.Location__c == null){
    				toDelete.add(aux.clone(true, true, true, true));
    			}
				else{
					aux.AddError('Cannot Delete if Location is Present');
				}
            }
    		
    	Trigger.new.clear();
    	
    	Trigger.new = toDelete.deepClone(true, true, true);
    
    }



Hope that it helps :)
Joan RubioJoan Rubio
Thanks Anupama and Agus!
Anupama SamantroyAnupama Samantroy
You are welcome!