+ Start a Discussion
chandan kumar 99chandan kumar 99 

contact record count

Hello Gurus:-
We have standard "Contact" object in SFDC.
and field is Total_Family_Member__c (number field )on the contact
object
my scenario is when contact is created in the same accountId then contact field (Total_Family_Member__c) is the update. 
my code
is :--
trigger Totalfamilymember2 on Contact (Before insert,Before update,Before delete,Before Undelete) {
   
set<id> ids = new set<id>();
    list<contact> contactToUpdate = new List<contact>();
    if(Trigger.isinsert||Trigger.isupdate|| Trigger.isundelete){
        for(contact con : trigger.new){
            if(con.AccountId != null){
               Ids.add(con.AccountId);
           }
        }
    }
    
    if(Trigger.isdelete){
        for(contact con : trigger.old){
            if(con.AccountId != null){
               Ids.add(con.AccountId);
           }
        }
    }
    
     for(AggregateResult ar :[SELECT AccountId,count(id) related FROM Contact  where AccountId in: Ids  GROUP BY AccountId]){
                    
                 contactToUpdate.add(new contact(Accountid = (Id)ar.get('AccountId'),Total_Family_Member__c= (Decimal)ar.get('related') ));
           }
                
               
    
}

Result is not show please find ???
Paul S.Paul S.
You're seeing nothing happen because you're essentially creating new contact records and adding them to a list but then never inserting them. 

You don't want to loop through the aggregate result query results, you want to build your aggregate result query first, then loop through the contacts in trigger.new and update the Total_Family_Member__c field based on the results from that aggregate result query.

Also, I'm not sure you'll get the correct number in a before context as I don't think a contact will "officially" be related to an account until after it's been inserted.  I believe you need to make this an after context trigger (you'll have recursiveness to handle, as well).