[SalesForce] Showing number of contacts in each account object

i created new custom field (Count_Of_Contact__c). then i written the trigger for update the related contact count, but did mistake.

it showing:

Compile Error: unexpected token: ')' at line 6 column 29

trigger countContact on contact(after insert, after Undelete){
set<Id> aId = new set<Id>();
List<contact> con = [select id from contact where accountId in:aId];
List<Account> acc = [select id, Count_Of_Contact__c from Account where Id in:aId];
if(trigger.Isinsert || trigger.IsUndelete){
for(contact ct = new contact){
aId.add(ct.accountId);
}
for(account ac = new account){
Count_Of_Contact__c = con.size();
}
}
update acc;
}

how can I fix the issue

Best Answer

It is advisable to use Aggregate Functions to count Contact records. It has performance benefit.

Refer Working with SOQL Aggregate Functions

trigger countContact on Contact (after update,after insert,after delete)
{
    Set<Id> Ids=new Set<Id>();

    if(Trigger.isInsert || trigger.isUpdate)
    {
        for(Contact Con: Trigger.New)
        {
            if(Con.AccountId!=null)
            {
                Ids.add(Con.AccountId);
            }
        }
    }
    if(Trigger.isUpdate || Trigger.isDelete)
    {
        for(Contact Con: Trigger.Old)
        {
            if(con.AccountId!=Null)
            {
                Ids.add(con.AccountId);
            }
        }
    }

    List<AggregateResult> results = [SELECT AccountId, Count(Id) ContactCount
                                     FROM Contact
                                     WHERE AccountId IN:Ids
                                     GROUP BY AccountId];
    List<Account> lstAccount = new List<Account>();
    for(AggregateResult result:results)
    {
        Account acct = new Account(Id= (Id) result.get('AccountId'), Count_Of_Contact__c = (Integer) result.get('ContactCount'));
        lstAccount.add(acct);
    }
    update lstAccount;
}

Note: I haven't compile the code but approach will be like that.