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
ChiyaChiya 

Need help in writing below code, ​​​​​​​Account cannot have more than 10 contacts,if user tries to add, user will get error.

Shubham Jain 338Shubham Jain 338
Hi Chiya,

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