Skip to main content
3 of 4
added 168 characters in body; edited tags; edited title
Adrian Larson
  • 151.4k
  • 38
  • 247
  • 431

Prevent Account Deletion based on Child Contact Status?

I have a requirement in which when click on delete button on the account it should allow you to delete only when its related contact status is inactive. I have written the following code which gives me list of contacts per account..

public class ContactsPerAccount{

    public static void contactResult()
    {
        Id accountId; // Fill in the accountId you want
        List<Contact> contacts = new List<Contact>([SELECT Id, Name,Inactive__c FROM Contact WHERE AccountId = :accountId]);
        System.debug(contacts);
        for(Contact c:Contacts){
            if(c.Inactive__c=Boolean.valueOf('true') )
            {
                System.debug('You Can not delete this account as its related contacts are Active');
            }
            else{
                System.debug('Go ahead ');
            }
        }
    }
}

If the Account contains any Contact whose Inactive flag is false it should throw an error message like

'You Can not delete this account as its related contacts are Active'...

In this case I have written a class here and I will use this class in trigger where I will use afterdelete event.. Can someone suggest how do I display an error message on UI after clicking on delete button..What else code do I need to modify? is it possible to write a separate class that I written and call it in trigger?

SFDCDJ
  • 1.9k
  • 7
  • 45
  • 86