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
AMAN SINGH 24AMAN SINGH 24 

hii.. I have a custom field(Number_of_contact__c) on account .I had written a trigger to update the field when a contact is created or deleted ,but it is not working.

trigger C1 on Contact (after insert,after delete) {
    decimal x;
  If (trigger.IsInsert==true){
   
for(contact c:trigger.new){
    If(c.Account!=null){
         Account a =new account();
         a=[select   Number_of_contact__c from account where account.name=:c.account.name];
         if(a.Number_of_contact__c==null){
         a.Number_of_contact__c=0;}
         x=a.Number_of_contact__c ; 
         x=x+1;
         a.Number_of_contact__c=x;
         update a;
         
           }
        }
     }   
   }
Best Answer chosen by AMAN SINGH 24
sfdcMonkey.comsfdcMonkey.com
or another easy way for it try below trigger code
rigger countcontacts on Contact (after delete, after insert, after undelete) {
    
    if(trigger.isAfter){
         set<id> setOfAccId = new set<id>(); // create a set of contact account id 
       if(trigger.isInsert  || trigger.isUnDelete){
            for(contact ocontact :trigger.New){   // play a for each loop at fill the set of id with account (id)
                 setOfAccId.add(ocontact.AccountId);   
            }  
       }
      if(trigger.isDelete){
             for(contact ocontact :trigger.old){
                setOfAccId.add(ocontact.AccountId);
            }
        }  
        
         // create a list for update Account 
         List<Account> accountUpdate = new List<Account>();
         List<Account> getacc = [Select Number_of_contact__c, Id, (Select Id From contacts) From Account WHERE ID IN :setOfAccId];
          for(Account acc :getacc){
             Integer ppCount = 0;
                for(contact ocon: acc.contacts){
                
                          ppCount++ ;
               
                } // inner for loop close
                
                if(acc.Number_of_contact__c != ppCount){
                 
                    acc.Number_of_contact__c = ppCount ;
                    accountUpdate.add(acc);
                 }
          }// outer for loop close
        
        if(accountUpdate.size() > 0){
          
          update accountUpdate ;
          
          }
    
       } // Trigger.isAfter closed
}
Let me inform if it helps you :)
 

All Answers

sfdcMonkey.comsfdcMonkey.com
hi Aman Singh
go to below link for your solution , you need to write trigger on after insert, after delete , after undelete , after update contact 
http://www.infallibletechie.com/2013/09/trigger-to-count-number-of-contacts.html
thanks
let me inform if it helps you and mark it best answer if my answer helps you so it make proper solution for others in future :)
sfdcMonkey.comsfdcMonkey.com
or another easy way for it try below trigger code
rigger countcontacts on Contact (after delete, after insert, after undelete) {
    
    if(trigger.isAfter){
         set<id> setOfAccId = new set<id>(); // create a set of contact account id 
       if(trigger.isInsert  || trigger.isUnDelete){
            for(contact ocontact :trigger.New){   // play a for each loop at fill the set of id with account (id)
                 setOfAccId.add(ocontact.AccountId);   
            }  
       }
      if(trigger.isDelete){
             for(contact ocontact :trigger.old){
                setOfAccId.add(ocontact.AccountId);
            }
        }  
        
         // create a list for update Account 
         List<Account> accountUpdate = new List<Account>();
         List<Account> getacc = [Select Number_of_contact__c, Id, (Select Id From contacts) From Account WHERE ID IN :setOfAccId];
          for(Account acc :getacc){
             Integer ppCount = 0;
                for(contact ocon: acc.contacts){
                
                          ppCount++ ;
               
                } // inner for loop close
                
                if(acc.Number_of_contact__c != ppCount){
                 
                    acc.Number_of_contact__c = ppCount ;
                    accountUpdate.add(acc);
                 }
          }// outer for loop close
        
        if(accountUpdate.size() > 0){
          
          update accountUpdate ;
          
          }
    
       } // Trigger.isAfter closed
}
Let me inform if it helps you :)
 
This was selected as the best answer
madhu sannapamadhu sannapa
See the below code:

trigger countoncontact on contact(After insert,after update,After delete)
{
if(trigger.IsAfter && trigger.isinsert)
{
set<ID>Idset1=new set<Id>();
for(contact con:trigger.new)
{
Idset1.add(con.AccountID);
}
list<Account>accupdatelist=new list<Account>();
list<Account>acclist=new list<Account>([select Id,Name,No_Of_Contacts__c,(select id,name,AccountID from Contacts ) from Account where ID In:Idset1]);
for(Account acc:acclist){
acc.No_Of_Contacts__c=Acc.contacts.size();
accupdatelist.add(acc);
}
update accupdatelist;
}
if(trigger.IsAfter && trigger.isupdate)
{
set<ID>IDset1=new set<ID>();
for(contact con:trigger.new)
{
if(con.AccountID!=trigger.oldmap.get(con.ID).AccountID)
{
Idset1.add(con.AccountID);
idset1.add(trigger.oldmap.get(con.ID).AccountID);
}
}
list<Account>accupdatelist=new list<Account>();
list<Account>acclist=new list<Account>([select Id,Name,No_Of_Contacts__c,(select id,name,AccountID from Contacts ) from Account where ID In:Idset1]);
for(Account acc:acclist){
acc.No_Of_Contacts__c=Acc.contacts.size();
accupdatelist.add(acc);
}
update accupdatelist;
}
if(trigger.IsAfter && trigger.isdelete)
{
set<ID>Idset1=new set<Id>();
for(contact con:trigger.old)
{
idset1.add(con.AccountID);
}
list<Account>accupdatelist=new list<Account>();
list<Account>acclist=new list<Account>([select Id,Name,No_Of_Contacts__c,(select id,name,AccountID from Contacts ) from Account where ID In:Idset1]);
for(Account acc:acclist){
acc.No_Of_Contacts__c=Acc.contacts.size();
accupdatelist.add(acc);
}
update accupdatelist;
}
if(trigger.IsAfter && trigger.isundelete){
Map<ID,set<ID>>AccMap1=new Map<ID,Set<ID>>();
for(Contact con:trigger.new)
{
if(AccMap1.ContainsKey(con.AccountID))
{
AccMap1.get(con.AccountID).add(con.ID);
}
else
{
AccMap1.put(con.AccountID,new set<ID> {con.Id});
}
}
list<Account>accupdatelist=new list<Account>();
list<Account>acclist=new list<Account>([select Id,Name,No_Of_Contacts__c,(select id,name,AccountID from Contacts ) from Account where ID In:AccMap1.Keyset()]);
for(Account acc:acclist){
acc.No_Of_Contacts__c=Acc.contacts.size();
accupdatelist.add(acc);
}
update accupdatelist;
}
}
AMAN SINGH 24AMAN SINGH 24
Can we do this by process builder also??
sfdcMonkey.comsfdcMonkey.com
as per my understanding NO , because process builder work  if  record is insert or  update only so , trigger is the best approch doing this task or you can do it by use rollup summery field on account object
thanks
AMAN SINGH 24AMAN SINGH 24
piyush_soni
 Could you please help me in writing the test class for this trigger?
Thanks in advance
sfdcMonkey.comsfdcMonkey.com
hi aman
please put a fresh question on forums related to test class. so with my answer other people take benefits of it. :)
thanks
AMAN SINGH 24AMAN SINGH 24
I am not able to find forums related to test class if you know then please send me the link.... Thank you
sfdcMonkey.comsfdcMonkey.com
bro i mean post new question on forum post your above trigger as a qustion for test class so everyone can see question
thanks