function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ramana123Ramana123 

1.Throw an error whenever the user try to delete the contact which is not associated to any account (when AccountId is null) how to write apex class and test class foe above requirement

Abdul KhatriAbdul Khatri
Hi Srikanth,

First of all Contact without AccountId can only possible through apex becuase through UI it is a mandatory field. This is not a best practise to have Contact without an AccountId. Please try to fix your data in the system as it consider a bad data.

It means that user are able to delete the Contact with AccountId? Is that true, that doesn't seem to be a good practise giving user to hard delete the data because deleting contact also delete it's associated data like Opportunity Contact Role etc. Are you taking care of that when allowing deletion. I meant when they delete there is no associated record exists.

Here you can use this trigger to achieve your goal.
trigger CantactCannotDeleteTrigger on Contact (before delete) {

    switch on Trigger.operationType 
    {
        when BEFORE_DELETE { 
            
            for(Contact contact : trigger.old) {
                
                if(contact.AccountId == null)
                {
                    contact.addError('Cannot delete without AccountId.');
                }
            }
        }  
    }    

}

 
Ramana123Ramana123
thanks for the code how to write test class for that code ..? can you please help me in that
Abdul KhatriAbdul Khatri
Here it is
@isTest
public class ContactTrigger_Test {

    static testMethod void test_contact_cannot_detele_without_account(){
        
        Contact contact = new Contact(LastName = 'Test');
        insert contact;
        
        try {
        	delete contact;
        } catch (Exception ex){
            system.assert(ex.getMessage().contains('Cannot delete without AccountId.'));
        }
    }  
}