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
krish@123krish@123 

Please help me it 's very urgent I have to display the contact records count created by individual users

HI 

Please check the below trigger iam getting the same records count from contacts for all users .

but  i need to display the contact records count created by individual users




trigger contactrecordcountresult on contact (before insert, before update) {

list<contact>ulist = new List<contact>();
ulist =[select id ,name, No_of_Assigned_Contacts__c,No_of_Converted_Contacts__c,No_of_Closed_Contacts__c,CreatedById  from contact];

list<AggregateResult>aglst = new list<AggregateResult>();

aglst =[select count(id) ,CreatedById from contact where   Customer_status__c <>'buyer broker'  group by CreatedById  ];
system.debug('----------------aglst ----------------fore-----'+aglst );

list<AggregateResult>aglst1 = new list<AggregateResult>();

aglst1 =[select count(id) ,CreatedById from contact where   Customer_status__c ='buyer broker'  group by CreatedById  ];
system.debug('----------------aglst1 ---------------------'+aglst1 );

list<AggregateResult>aglst2 = new list<AggregateResult>();

aglst2 =[select count(id) ,CreatedById from contact where   Customer_status__c ='closed'  group by CreatedById  ];



for (AggregateResult ar : aglst )
{
  
   for(contact uu:trigger.new){
   
 
   uu.No_of_Assigned_Contacts__c =  Integer.valueOf(ar.get('expr0'));
  
  
 }
  
 }
 //update ulist;
 
  
 for (AggregateResult ar1 : aglst1 )
{
for(contact uu1:trigger.new){
   uu1.No_of_Converted_Contacts__c=  Integer.valueOf(ar1.get('expr0'));

 }
 
 }
 
  for (AggregateResult ar2 : aglst2 )
{
for(contact uu2:trigger.new){

   uu2.No_of_Closed_Contacts__c=  Integer.valueOf(ar2.get('expr0'));
   
 }

 }
 

It's vry urgent 


Thanks
Best Answer chosen by krish@123
Shashikant SharmaShashikant Sharma
Your trigger only needs to be on after insert as created by fied is not updatable.
// use below code


list<AggregateResult> aglst2 =[select count(id) ,CreatedById from contact where  CreatedById =:Userinfo.getUserId() and  Customer_status__c ='closed'  group by CreatedById  ];

// current user
User userObj = new User( Id = Userinfo.getUserId() );
userObj .No_of_Assigned_Contacts__c =  Integer.valueOf(ar.get('expr0'));
update userObj;