+ Start a Discussion
Rick SF AdminRick SF Admin 

Custom field that counts and displays the number of records within a custom object

Hi,
I have a custom object (Demo__c). In this object, I would like to have a custom field that would count and display the number of records for this object based on a filter criteria. I know this can be accomplished using Reports but I want a field on the object itself to show this information. For example, the Demo object has 100 records. Of the 100 records, I want to see in this custim field how many records have a total revenue value less than or $1,000,000. If there are 10, then the custom field should show 10. 
Akshay_DhimanAkshay_Dhiman
Hi Rick,
You can try this code:

TRIGGER HANDLER:
 
public class Democount {
 public static void countrecords(List<Demo__c> deList)
 {
     system.debug('deListdeList->'+deList);
     List<Demo__c> dbList=[select name,total_revenue__c,Count__c from Demo__c ];
     List<Demo__c> deList1=new List<Demo__c> ();
     for(Demo__c de:dbList)
     {
         if(de.total_revenue__c<=1000000)
         {
            deList1.add(de); 
         }
     }
     
     Integer size = deList1.size();
     List<Demo__c> deList2=new List<Demo__c> ();
     for(Demo__c de1:deList1)
     {
         de1.Count__c=size;
       
     }
     update deList1;
 }

}


TRIGGER:
 
trigger Demotrigger on Demo__c (after insert,after update) {
    if(checkRecursion.runOnce()){
         Democount.countrecords(trigger.new);

    }

}

/*here, in this program we need to create one more class that will restrict recursion to happen because of after update trigger*/

public Class checkRecursion{

        private static boolean run = true;
        public static boolean runOnce(){
          if(run){
           run=false;
           return true;
          }else{
            return run;
          }
        }
    }


Hope this explanation will help you. 
If you find it helpful, mark it as best answer so that other's also get help from this.

Thanks,
Akshay