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
Nitin SharmaNitin Sharma 

How to write a trigger to don't allow user to create more than 3 contact on an a account

Bhanu MaheshBhanu Mahesh
Hi Nitin,

Try below code
 
trigger restrictContactCreation on Contact(before insert){
    Set<Id> accountIds = new Set<Id>();
    Map<Id,Integer> mapAccountIdWithContactCount = new Map<Id,Integer>();
    for(Contact con : trigger.new){
        if(con.AccountId != null){
            accountIds.add(con.AccountId);
        }
    }
    if(!accountIds.isEmpty()){
        for(Account acc: [SELECT Id,(SELECT Id FROM Contacts) FROM Account WHERE Id IN : accountIds]){
            Integer conCount = 0;
            if(acc.Contacts.size() > 0){
                conCount = acc.Contacts.size();
            }
            mapAccountIdWithContactCount.put(acc.id,conCount);
        }
    }
    
    for(Contact con : trigger.new){
        if(con.AccountId != null && mapAccountIdWithContactCount != null && mapAccountIdWithContactCount.get(con.AccountId) != null){
            if(mapAccountIdWithContactCount.get(con.AccountId) >= 3){
                con.addError('You cannot create more than three contacts for an account');
            }
        }
    }
}

Mark this as "SOLVED" if your query is answered.

Thanks & Regards,
Bhanu Mahesh Gadi