function readOnly(count){ }
Don't have an account?
Search for an answer or ask a question of the zone or Customer Support.
You need to sign in to do that
Sign in to start searching questions
Signup for a Developer Edition
Sign in to start a discussion
trigger CountOfContact on Contact (after insert) { //NumberofLocations__c Set<Id> aId = new Set<Id>(); List<Account> accToUpdate= new List<Account>(); map<id,List<Contact>> conMap = new map<id,List<Contact>>(); for(Contact c :trigger.New){ if(c.accountId!=null){ if(conMap.get(c.AccountId)==null){ conMap.put(c.AccountId,new List<Contact>()); } conMap.get(c.AccountId).add(c); aId.add(c.AccountId); } } if(aId.size() > 0){ List<Account> accList=[select name,Total_Contact__c from Account where id in:aId]; for(Account a : accList){ a.Total_Contact__c= conMap.get(a.Id).size(); accToUpdate.add(a); } update accToUpdate; }
trigger updateContactCountOnAccount on Contact (after insert, after update, after delete, after undelete) { Set<Id> AccountIds = new Set<Id>(); if(!Trigger.isDelete){ for (Contact ct : Trigger.new) { if(Trigger.isInsert && ct.AccountId != null){ AccountIds.add(ct.AccountId); } //For Contact Update scenarios, Contact.AccountId value should be checked for null in new and old record. if(Trigger.isUpdate){ if(ct.AccountId==null && Trigger.oldMap.get(ct.Id).AccountId != null){ AccountIds.add(Trigger.oldMap.get(ct.Id).AccountId); } if(ct.AccountId!=null && Trigger.oldMap.get(ct.Id).AccountId != null && ct.AccountId != Trigger.oldMap.get(ct.Id).AccountId){ AccountIds.add(ct.AccountId); AccountIds.add(Trigger.oldMap.get(ct.Id).AccountId); } if(ct.AccountId!=null && Trigger.oldMap.get(ct.Id).AccountId == null){ AccountIds.add(ct.AccountId); } } if(Trigger.isUndelete && ct.AccountId != null){ AccountIds.add(ct.AccountId); } } }else{ for (Contact ct : Trigger.old){ if(Trigger.isDelete && ct.AccountId != null){ AccountIds.add(ct.AccountId); } } } List<Account> AcctToUpdate = new List<Account>(); //AggregateResult to get count of Contact for each Account for (AggregateResult ar: [Select Count(Id) ContactCount, AccountId from Contact where AccountId IN: AccountIds GROUP BY AccountId]){ Account tmp = new Account(Id=(Id)ar.get('AccountId'), NumberContacts__c=(Decimal)ar.get('ContactCount')); AcctToUpdate.add(tmp); } if(AcctToUpdate.size()>0) update AcctToUpdate; }
Try this code to fetch a number of contacts in Account
If found this helpful mark it as best so that it helps others in solving the same.
Thanks
Akshay
Please try the below code. Hope it helps you.
It will work for all the operations delete, insert, update.
you need to replace this field with "NumberContacts__c" your custom field "Total_Contact__c"
Please select as best answer if it helps you.
Thank You,
Ajay Dubedi