-5

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).

2
  • 2
    Stackoverflow is not a code writing service. Give some examples of what you have tried and possibly you will get an advise of what to fix Jul 19, 2016 at 8:52
  • I'm voting to close this as off-topic because it is not even a question.
    – martin
    Jul 20, 2016 at 3:01

3 Answers 3

4

You can do this in before delete trigger. You can check and addError to prevent user from deleting the record.

trigger AccountTrigger(before delete){
    for(Account acc: Trigger.old){
        if(acc.location__C!=null){
            acc.AddError('Cannot Delete if Location is Present');
        }
    }
}

Trigger.new and Trigger.newMap is not available in delete operation.

0

Here are steps to achieve your goal:

  • Write a trigger on Account, trigger event will be Before Delete.
  • For the accounts which do have the location, use the addError() method to display the Trigger Exceptions.
  • Also for the DML performed in the apex class use the Bulk DML Exception to add error to the records.
1
  • Please Mark this answer as accepted if this achieves your goal and comment below for any questions. Jul 19, 2016 at 8:59
0

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 not empty');
            }
        }

    Trigger.new.clear();

    Trigger.new = toDelete.deepClone(true, true, true);

}

Hope that it helps :)

Not the answer you're looking for? Browse other questions tagged .