0

Is there a way to fire an existing Validation Rule from apex. Specifically, I want to fire the rule during a "before delete" trigger.

1

You can not not invoke validation rule from Apex.

As I understand your requirement is to apply validation rule at Delete event; But as this event is not supported in Validation rule by Salesforce you try to use existing validation rule from Apex trigger. Only workaround is to use addError() something like below:

trigger validation_using_Trigger on Account (before delete) {
 for(Account acc:trigger.old){
    if(acc.AnnualRevenue < 2000){
       acc.adderror('Annual revenue cannot be less than 2000');
    }
 }
}

Although it will not be more controllable/customizable in compare with Validation rule but you can use Custom Setting or Metadata Type to store condition, error message or rule status (whether rule is active or not) to make it configurable and more admins controllable.

| improve this answer | |
  • Thanks. This actually stemmed from a bad requirement description. They were stating that they wanted the validation rule to fire, where, as like you stated, they just wanted validation to occur before delete. – aaron May 23 '18 at 18:52
  • Yes...system admin do not love code..they always look for configuration so that they can update the criteria...change the message...activate/deactivate anytime... – Ayub May 23 '18 at 18:59
3

From your question, I gather you're attempting to prevent a deletion based on criteria defined in a validation rule. Unfortunately, this can't be done via a validation rule.

Also, you cannot apply a validation rule directly to a record via APEX. The only way to apply a validation rule would be to perform an insert or update database operation. Since you can't update the records within the trigger in a before trigger, you can't trick the system into using a validation rule and since you can't update them in the after (because they have been deleted) you can't trick it there either.

If you want to prevent users from deleting a record, this can be done pretty easily in a before delete trigger. Below is a very simple example of howed you do that. You should be able to adapt this to your needs.

if (Trigger.isBefore && Trigger.isDelete) {
    for (record r : trigger.Old) {
        if (r.ClosedDate > system.today()) {
            r.addError('Cannot delete records that have not yet closed');
        }
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.