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
Karthik keyanKarthik keyan 

To show the contact count details in account details page

In account page,the contact is created ,I want to show the number of count of contacts records created that is associated with that account.I have tried to write the trigger for that.But some error getting in that trigger.Please rectify to solve that bugs.    

trigger NoofCountContacts on Account (after insert,after update) {
   List <Account> con = new List <Account>();
   for (contact con1:Trigger.new){
      String Id= Apexpages.currentPage().getParameters().get('Account.Id');
   Integer sum =[SELECT COUNT() FROM contact where accid =:Trigger.old.keyset(Id)];
   con.Number_Of_Contacts= sum;
   }
   update con;
   }
Tushar sharmaTushar sharma
what error you are getting . i think you don't give correct Id lease check your id in system.debug may be that is the problem and if you are duisplay detail in custom vF page then you can use this code controllr of the age you don't need to write trigger for this. for any other query feel free to ask
Sree SalesforceSree Salesforce
Both objects have master-detail relationship .then we can perform rollup summary operation.we can find the count of contacts.
or if the records have lookup relationship we can write a trigger .

Sree SalesforceSree Salesforce
count of contacts you have a look up relationship
trigger countofcontact on Account (after insert,before update) {
 
  list<id> l1=new list<id>();
  list<account> listacc=new list<account>();
  list<contact> listcon=new list<contact>();
  map<id,integer> m1=new map<id,integer>();

 for(account acc:trigger.new)
 {
  l1.add(acc.id);
  }
  for(account a1:trigger.old)
  {
   l1.add(a1.id);
   }
   
   list<account> l=[select id,name from account where id in:l1];
   list<contact> lc=[select id,name from contact where id in:l1];
   
   for(account a:trigger.new)
   {
    
    listcon.clear();
    for(contact con:lc)
    {
     listcon.add(con);
     m1.put(con.accountid,listcon.size());
     }
     
     }
    if(listcon.size()>0)
    {
     for(account aa:l)
     {
       if(m1.get(aa.id)==null)
     {
      aa.count_of_contact__c=0;
      }
      else
      {
     aa.count_of_contact__c=m1.get(aa.id);
     l.add(aa);
     
     }
     }
     }
     if(l.size()>0)
     {
     update l;
     
     }}