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
Nisha Kumar 1Nisha Kumar 1 

Throw an error whenever the user tries to delete the contact which is not associated to account

Best Answer chosen by Nisha Kumar 1
HARSHIL U PARIKHHARSHIL U PARIKH
Try this:
 
Trigger NoAccountIdNoDelete on Contact (Before Delete) {
	
    If(Trigger.IsDelete){
        For(Contact Con : Trigger.Old)
        {
            If(Con.AccountId == NULL)
            {
              Con.addError('You cannot delete the contact who does not have any associated account');  
            } 
        }
    }
}

Hope this helps! 

All Answers

Ajay K DubediAjay K Dubedi
Hi Nisha,

Please try the below code.

// Apex Class

public class Default_CreateContact {
    public static void createContact(List<Contact> contList)
    {
        for(Contact con: contList)
        {
            if(con.AccountId == NULL)
            {
                con.addError('You Can not delete the account');
            }
        }
    }
}

// Trigger

trigger deleteContact on Contact (before delete) {
    
    if(Trigger.IsDelete && Trigger.IsBefore)
    {
       Default_CreateContact.createContact(Trigger.old);
    }
}

Please select it as best answer if you find it helpful

Thank You,
Ajay Dubedi
HARSHIL U PARIKHHARSHIL U PARIKH
Try this:
 
Trigger NoAccountIdNoDelete on Contact (Before Delete) {
	
    If(Trigger.IsDelete){
        For(Contact Con : Trigger.Old)
        {
            If(Con.AccountId == NULL)
            {
              Con.addError('You cannot delete the contact who does not have any associated account');  
            } 
        }
    }
}

Hope this helps! 
This was selected as the best answer