Skip to main content
1 of 4
SFDCDJ
  • 1.9k
  • 7
  • 45
  • 86

How to delete an account based on the status of contacts

I have a requirement inwhich 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 contacts = new List([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 the contact of status active 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