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

Count number of Contacts for Particular Account

Take a number field on Account. Whnever a Contact is inserted for a particular account, number value in accoutn ahould be increamented by 1.

Jerun JoseJerun Jose
Use a trigger which fires on insert of contact to increment the accout field.

You could probably use a cross object workflow to do this



Try this code......


List<contact> conforaccounts = [select id,Accountid from contact];

List<Account> Noofcontacts = [select id,No_of_Contacts__c from Account];

for (Account acct : Noofcontacts) {

list<ID> conIds = new list<ID>();

for (Contact con : conforaccounts ) {

if (con.AccountId == acct.Id)
acct.No_of_Contacts__c = conIds.size();


update Noofcontacts;

trigger updateAccounts on Contact(after insert, after update, after delete, after undelete) {
    Set<id> accounts = new Set<Id>();
    if(trigger.old != null)
        for(contact c:trigger.old)
    if( != null)
    update [select id from account where id in :accounts];
trigger countContacts on Account (before update) {
        a.no_of_contacts__c = 0;
    for(aggregateresult ar:[select accountid accountid, count(id) contactcount from contact where accountid in :trigger.newmap.keyset() group by accountid])
        trigger.newmap.get((id)ar.get('accountid')).no_of_contacts__c = (decimal)ar.get('contactcount');

First trigger calls the parent records for updating. The second performs a summed query. This makes sure that contacts do not "slip through the cracks" and are always counted correctly.





still no body give best solution or at least hint to solve. 

List<Account> acc=new List<Account>();
List<Contact> contTemp =new List<Contact>();
        contTemp.lastname =;
        contTemp.accountid = acc.Id;
        insert c;

for(account a: acc)
  integer i=0;
    List<Contact> contTemp =new List<Contact>();
  if([select count() from contact where]>0){


 i tried like this am new lerner. somuch mistakes. and atleast give a hint which concepts cover in this assignment.


Plenty of answers were given, but none seemed to satisfy your request, so I'm afraid I have no idea what you're asking. Your code makes no sense whatsoever, and your objective is unclear. What are you hoping to achieve, besides the generic description you provided in your original post?

Hi sfdcfox,
Thanks for posting the code for calculating the count.
I was trying to figure out in your code, why we need Account trigger to update count. Can't we do it through the Contact Trigger only thus saving a SOQL?