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
punit tyagi 12punit tyagi 12 

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY:

Error:  CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: contacttrigger: execution of AfterInsert caused by: System.ListException: Duplicate id in list: 0015g00000bIctOAAS Class.counttriggercontact.countcontact: line 39, column 1 Trigger.contacttrigger: line 15, column 1 []

public class counttriggercontact {
    
    public static void countcontact (List<Contact> conlist)
    {
        system.debug('inside the method');
        Map<String,list<contact>> accountcontactmap = new map<String,list<contact>>();
        Set<id> accountidset = new set<id>();
        for(contact con:conlist)
        {
            accountidset.add(con.accountid);
        }
        List<contact> alreadyaccount = [select id,accountid from contact where accountid in:accountidset];
        for(contact c:alreadyaccount)
        {
            if(accountcontactmap.containskey(c.accountid))
            {
                list<contact> conlist1 = accountcontactmap.get(c.accountid);
                conlist1.add(c);
                accountcontactmap.put(c.accountid,conlist1);
            }
            else
            {
                list<contact> newlist = new list<contact>();
                newlist.add(c);
                accountcontactmap.put(c.accountid,newlist);
            }
        }
        list<account> acclist = new list<account>();
        for(contact cobj:conlist)
        {
            list<contact> presentcontact = accountcontactmap.get(cobj.AccountId);
            account acc = new account ();
            acc.id = cobj.AccountId;
            acc.No_of_Contact__c = presentcontact.size();
            acclist.add(acc);
           
            
        }
        update acclist;
        
        
    }

}

AnkaiahAnkaiah (Salesforce Developers) 
Hi Punit,

try with below code.
trigger CountContactOnAccount on Contact (after INSERT, after UPDATE, after DELETE ) {
Set <Id> accountIds = new Set <Id>();
List <Account> lstAccountsToUpdate = new List <Account>();
 if(Trigger.isInsert){
    for(Contact con:trigger.new){
        accountIds.add(con.accountID);
    }
}
if(Trigger.isUpdate|| Trigger.isDelete){
    for(Contact con:trigger.old){
        accountIds.add(con.accountID);
    }
}

for(Account acc:[SELECT Id,Name,Count_Contact__c,(Select Id from Contacts) from Account where Id IN: accountIds]){
    Account accObj = new Account ();
    accObj.Id = acc.Id;
    accObj.Count_Contact__c = acc.Contacts.size();
    lstAccountsToUpdate.add(accObj);
}

UPDATE lstAccountsToUpdate;

Refer the below link.
https://salesforce.stackexchange.com/questions/138455/count-the-contacts-in-the-related-list-of-account-and-display-the-contact-count

If this helps, please mark it as best answer.

Thanks!!​​​​​​​