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
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.');
}
}
}
}
}
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.