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
Harish PHarish P 

Write A trigger like (Trigger Trigger_Name On Account(After insert, After update) For count the Number of contacts related to particular account, and display count value in account Object..., Anyone give proper answer for this

GouthamGoutham
Hi Harish,
Trigger should be written on Contact as Account is Lookup on it.Also Account should be updated ​when contact got deleted.
Trigger contactTrigger on Account(After insert, After update){
	if(trigger.isAfter){
		if(trigger.isInsert)
			updateAccountWithcontactsCount.contactsCount(trigger.new,null,'insert');
		if(trigger.isUpdate)
			updateAccountWithcontactsCount.contactsCount(trigger.new,trigger.oldmap,'update');
		if(trigger.isDelete).
			updateAccountWithcontactsCount.contactsCount(trigger.old,trigger.oldmap,'delete');
	}
}
 
public class updateAccountWithcontactsCount{
	
	puclic static void contactsCount(list<Contact>contactList, Map<id,Contact>oldMap,String triggerAction){
		boolean isInsert = (contactList==null);
		
		set<ID> accIds = new set<ID>();
		Map<Id,Account> accountMap = new Map<Id,Account>();
		Map<Id,list<Contact>> accountRelatedCOntactsMap = new Map<Id,list<Contact>>();
		list<Account> updateAccount = new list<Account>();
		for(Contact con : contactList){
			if((isInsert && con.AccountId != null)|| (! isInsert && con.AccountId != null && con.AccountId != oldMap.get(con.id).AccountId) 
				|| (triggerAction == 'delete' && con.AccountId != null))
			accIds.add(con.AccountId);
		}
		if(!accIds.isEmpty()){
			for(Account acc : [select id ,(select id from contacts) from Account where ID IN : accIds]){
				accountMap.put(acc.id,acc);
				
				if(accountRelatedCOntactsMap.get(acc.id)==null)
					accountRelatedCOntactsMap.put(acc.id,new list<Contact>{});
				if(accountRelatedCOntactsMap.get(acc.id)!=null)
					accountRelatedCOntactsMap.get(acc.id).addAll(acc.contacts);
			}
		}
		if(!accountRelatedCOntactsMap.isEmpty()){
			for(Contact con : contactList){
				accountMap.get(con.AccountId).count__c=accountRelatedCOntactsMap.get(con.AccountId).size()
				updateAccount.add(accountMap.get(con.AccountId));
				
			}
		}
		if(! updateAccount.isempty()){
			update updateAccount;
		}
	}
}

 
Chetan KapaniaChetan Kapania
Getting following error while trying to save class:
Line 27: Illegal assignment from List to Decimal

Error while trying to save trigger:
Line 4: Method does not exist or incorrect signature: void contactsCount(List<Account>, NULL, String) from the type updateAccountWithcontactsCount
Line 6: Method does not exist or incorrect signature: void contactsCount(List<Account>, Map<Id,Account>, String) from the type updateAccountWithcontactsCount
Line 8: Method does not exist or incorrect signature: void contactsCount(List<Account>, Map<Id,Account>, String) from the type updateAccountWithcontactsCount

How to rectify these errors?

Regards
Chetan
Shamsi 110Shamsi 110
Trigger countContactsOnAccount on Account(After Insert , After Update)
{

if(trigger.isInsert && Trigger.IsAfter)
AfterInsertLogic(Trigger.new);
}
if(trigger.isUpdate && Trigger.IsAfter)
AfterUpdateLogic(Trigger.new,Trigger.OldMap);
}


Public static class calcuateCOntactCOunt()
{

Public static AfterInsertLogic(List<Account> listAcc)
{
set<Id> accountIDS = new Set<Id>();
List<Account> count = new List<Account>();

for(Account acc :listAcc){
accountIDS.add(acc.id);
}

Integer contactCounts = [Select count(Id) from contacts where accountid in :accountIDS];

for (Account a : accountIDS)
{
 Account a = new Account(id=a.Id,countfield=contactCOunts);
 count.add(a);
}
if(count.size()>0)
{
update count;
}

}
Public static AfterUpdateLogic()
{
// write something like insert

}
}

 
Chetan KapaniaChetan Kapania
Tried the code but getting these error messages:
unexpected syntax:'mismatched input '('expecting LCURLY' with apex class on Line 1
Method does not exist or incorrect signature: void AfterInsertLogic(List<Account>) from the type countContactsonAccount on trigger
Method does not exist or incorrect signature: void AfterUpdateLogic(List<Account>, Map<Id,Account>) from the type countContactsonAccount on trigger
Suraj TripathiSuraj Tripathi

Hi Harish,
Please try this piece of code. Hope it will help you.

Trigger : ​
 

trigger ContactCount_Account on Account (after insert, after Update) {
    if(trigger.isAfter && (trigger.isInsert || Trigger.isUpdate)){
        Accout_contact_count.test(Trigger.new,Trigger.oldMap);
    }
}
Hanler :
public class Accout_contact_count {
    public static void test(List<Account> Accounts, Map<Id, Account> accMap){
        set<id> account_Id = new set<id>();
        List<Account> AccountUpdate = new List<Account>();
        
        map<Id,Integer> mp1 = new map<id,Integer>(); 
        for(Account acc : Accounts){
            account_Id.add(acc.id);
        }
        
        List<Contact> contactList = new List<Contact>();
        contactList = [select id,LastName,AccountId from Contact where AccountId =: account_Id];
        if(contactList.size()>0){
            Integer count = 0;
            for(Id AccId : account_Id){
                for(Contact cnn : contactList){	
                    if(cnn.AccountId == AccId){
                        count = count+1;
                    }
                }
                mp1.put(AccId,count);
                count = 0;
            }
            for(Id accid : account_Id){
                if(mp1.containsKey(accid) && accMap.get(accid).Contact_count__c != mp1.get(accid)){
                    Account accountList = new Account();
                    accountList.id = accid;
                    accountList.Contact_count__c = mp1.get(accid);
                    AccountUpdate.add(accountList);
                }
            }
            if(AccountUpdate.size()>0){
                update AccountUpdate;
                System.debug(AccountUpdate);
            } 
        }
        else{
            for(Id accid : account_Id){
                Account accountList = new Account();
                accountList.id = accid;
                accountList.Contact_count__c = 0;
                AccountUpdate.add(accountList);
            }
            if(AccountUpdate.size()>0){
                update AccountUpdate;
                System.debug(AccountUpdate);
            } 
        }
    }
}

If this code helps you. Please m ark it as best.

Regards,
Suraj
Chetan KapaniaChetan Kapania
Tried the code... but somehow it is not working. Giving error in regards to variable does not exist.