Skip to main content
2 of 2
deleted 47 characters in body
Adrian Larson
  • 151.4k
  • 38
  • 247
  • 431

You need to use the SObject.addError method. Note that you can only pass in records from the trigger context as a parameter value.

I recommend modifying your method to accept the trigger records. Best practice is to put the error message in a Custom Label so you can configure this user-facing copy quickly and easily. Something like:

public static void validateNoActiveContacts(Map<Id, Account> records)
{
    Set<Id> withActiveContact = new Map<Id>([
        SELECT Id FROM Account WHERE Id IN (
            SELECT AccountId FROM Contact
            WHERE Inactive = false
            AND AccountId IN :records.keySet()
        )
    ]).keySet();
    for (Id accountId : withActiveContact)
        records.get(accountId).addError(Label.Active_Contact_Error);
}
Adrian Larson
  • 151.4k
  • 38
  • 247
  • 431