trigger ContactTrigger on Contact (after insert, after update, after delete, after undelete) {
List<Contact> contactList = Trigger.isDelete ? Trigger.Old : Trigger.New; Set<Id> accountIdSet = new Set<Id>(); Map<Id, Contact> contactMap = new Map<Id,Contact>(); for (Contact con : contactList) { if (Trigger.isUpdate) { if (con.AccountId != Trigger.oldMap.get(con.Id).AccountId) { if (con.AccountId != null) accountIdSet.add(con.AccountId); if (Trigger.oldMap.get(con.Id).AccountId != null) { accountIdSet.add(Trigger.oldMap.get(con.Id).AccountId); contactMap.put(Trigger.oldMap.get(con.Id).AccountId, con); } } } else if (con.AccountId != null) { accountIdSet.add(con.AccountId); } if (con.AccountId != null) contactMap.put(con.AccountId, con); } if (accountIdSet.size() > 0) { List<Account> accountList = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :accountIdSet]; if (accountList.size() > 0) { for (Account acc : accountList) { if (acc.Contacts.size() > 10 && contactMap.containsKey(acc.Id)) { contactMap.get(acc.Id).addError('An account can not have more than 10 contacts.'); } } } } }
trigger ContactTrigger on Contact (after insert, after update, after delete, after undelete) {
List<Contact> contactList = Trigger.isDelete ? Trigger.Old : Trigger.New;
Set<Id> accountIdSet = new Set<Id>();
Map<Id, Contact> contactMap = new Map<Id,Contact>();
for (Contact con : contactList) {
if (Trigger.isUpdate) {
if (con.AccountId != Trigger.oldMap.get(con.Id).AccountId) {
if (con.AccountId != null) accountIdSet.add(con.AccountId);
if (Trigger.oldMap.get(con.Id).AccountId != null) {
accountIdSet.add(Trigger.oldMap.get(con.Id).AccountId);
contactMap.put(Trigger.oldMap.get(con.Id).AccountId, con);
}
}
} else if (con.AccountId != null) {
accountIdSet.add(con.AccountId);
}
if (con.AccountId != null) contactMap.put(con.AccountId, con);
}
if (accountIdSet.size() > 0) {
List<Account> accountList = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :accountIdSet];
if (accountList.size() > 0) {
for (Account acc : accountList) {
if (acc.Contacts.size() > 10 && contactMap.containsKey(acc.Id)) {
contactMap.get(acc.Id).addError('An account can not have more than 10 contacts.');
}
}
}
}
}
Please mark this as the best answer if it helps
Thanks
Shubham Jain