Scenario:While inserting Contact check if linked Account is already associated to other Contact. Throw Error is yes.
ContactTrigger
trigger ContactTrigger on Contact (before insert) {
if(trigger.isBefore && trigger.isInsert) {
ContactTriggerHandler.checkIfAccountAlreadyLinked(trigger.new);
}
}
ContactTriggerHandler
public class ContactTriggerHandler {
// Scenario: While inserting Contact check if linked Account is already associated to other Contact. Throw Error is yes.
public static void checkIfAccountAlreadyLinked(List<Contact> lstContact) {
Set<String> setAccIds = new Set<String>();
Map<String, Id> oldContactsMap = new Map<String, Id>();
for(Contact con: lstContact) {
if(con.AccountId != null) {
// Note : Here we can't check con.AccountId != '' - because An ID isn't ever N/A. It will always be one of null
setAccIds.add(con.AccountId);
}
}
for(Contact con: [Select Id, AccountId From Contact Where AccountId in: setAccIds]) {
oldContactsMap.put(con.AccountId, con.Id);
}
for(Contact con: lstContact) {
if(con.AccountId != null && oldContactsMap.containsKey(con.AccountId)) {
con.AddError('Contact with same Account already exist.');
}
}
}
}