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
Rick SF AdminRick SF Admin 

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

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. 
Hi Rick,
You can try this code:

public class Democount {
 public static void countrecords(List<Demo__c> 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)
     Integer size = deList1.size();
     List<Demo__c> deList2=new List<Demo__c> ();
     for(Demo__c de1:deList1)
     update deList1;


trigger Demotrigger on Demo__c (after insert,after update) {



/*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(){
           return true;
            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.