Rollup summary trigger for lookup relationship

Rollup Summary Trigger for Lookup Relationship to count child records

How to Create a rollup summary trigger for lookup relationship.

Before we Startup with the Trigger let’s check out with admin part that has to be done.

  • First Create 2 Objects “Class” later “Student”
  • Create a Lookup Relationship field on “Student” for “Class” with the name “Class”.
  • Create a Number field on “Class” with the name “Number of Students”.

Let’s also learn something needed which is on which object we should write the Trigger. So as we know whenever the Student gets inserted or updated or deleted or undeleted we need to update Class, that is whenever there are Changes in Student then we should do changes in Class. So initial changes is taking place in Student that is the reason we need to write the Trigger on Student.

Now we are ready with the admin part to let see when we should call this trigger, so as per the question we should get the number of students related to a particular class on the Class Object field. So according toΒ  it when will the Number of Students change in Class Object, it is

  • When we Create a new Student
  • When a Student is updated and only if the Class field changes
  • When a Student is deleted
  • When a Student is undeleted

So by this, we come to know we should call this Trigger during “insert, update, delete and undelete”. Now the next thing that we should focus on is whether we should use “after” or “before” Trigger. Hereafter the Student is getting inserted only we come to know which class he belongs to and then later we will increment the Number of Students for that particular Class which the Student belongs. The same goes with the update, delete and undelete also, this is the reason that we have to use “after” Trigger.

Now let’s get into the coding, there are some things we have to check those are,

  1. During Insert and Undelete(i.e. we are again adding or inserting back the deleted data) we should check whether the newly inserted data(i.e. Trigger.new) is not null and loop all the data and check if the Class field is not null, if it is not null then we can add that Class Id to a list for later use.
  2. During Delete, we are deleting the existing data(i.e. Trigger.old) is not null and loop all the data and check if the Class field is not null, if it is not null then we can add that Class Id to a list for later use.
  3. But when it comes to Update we should just check if the Class field is changing, so we will compare old and new data of the Class field if that is not equal that means the Students class has changed and we should decrement 1 student in the old Class and increment 1 in new Class, so we will check if the old and new Class fields or not null, then add those Class Id to the list.

Now that we have collected the Id of Class in the Set<Id>, we would get the count of Students associated to particular Class using the SOQL query ” Select count(Id), Class__c from Student__c where group by Class__c”. Now we use this query to get the Class Id and it corresponding count of students associated to it for only the Class Id’s which are present in Set<Id> and adding those values to a Map<String, Double> where String contains Class Id and the Double contains the Number of count of Students associated to it. Now get all the records of the Class which is present in Set<Id> into a List<Class__c> and check if that particular Class Id is present in the Map<String, Double>, if present then we are getting it value and placing it in the Number_of_Students__c field if not we are passing null value to the Number_of_Students__c field. Later we are checking if the List<Class__C> not empty then we are updating the list.

Spread the love

Related Posts

6 thoughts on “Rollup Summary Trigger for Lookup Relationship to count child records

  1. dear chaitra , I have tried this trigger on Account and contact object but this code is not working while delete,insert and update Child(Contact) record. anyone in community have solution for this??

  2. trigger CountContactOnAccount on Contact (after INSERT, after UPDATE, after DELETE, after UNDELETE )
    {
    Set accountIds = new Set ();
    if(Trigger.isInsert||Trigger.isUndelete)
    {
    if(Trigger.new !=null)
    {
    for(Contact con:Trigger.new)
    {
    if(con.AccountId !=null)
    {
    accountIds.add(con.AccountId);
    }
    }
    }
    }
    if(Trigger.isDelete)
    {
    if(Trigger.old!=null)
    {
    for(Contact con:trigger.old)
    {
    accountIds.add(con.accountID);
    }
    }
    }

    if(Trigger.isUpdate)
    {
    for(Contact con:trigger.new)
    {
    if((con.AccountId != trigger.oldMap.get(con.Id).accountID) && (trigger.oldMap.get(con.Id).accountID != null))
    {
    accountIds.add(trigger.oldMap.get(con.Id).accountID);
    if(con.AccountId!= null)
    {
    accountIds.add(con.AccountId);
    }
    }
    }
    }

    List accList = [SELECT Id,Count_of_Contacts__c,(Select Id from Contacts) from Account where Id IN: accountIds];
    system.debug(accList);

    if(accList!=null)
    {
    for(Account AccObj : accList)
    {
    AccObj.Count_of_Contacts__c = AccObj.Contacts.size();
    }
    }
    if(accList.size()>0)
    {
    update accList;
    }
    }

    1. Hi Ishan,
      Your Declaration for “Set” is wrong change it. And the declaration of ” List ” is also wrong change it. And check for the API name of ” AccountId ” you have written it as ” accountId “.It will work after you change these things.

      Thank you

  3. It is not preferred to use sub query, suggestion would be to use an aggregate result as using a sub query comes with the limit of 200 records

  4. The above mentioned solution will fail, if in case each account already has 50k contacts associated and you try to update one contact.
    Query will fail and throw 50001 query exception.

    1. Hi Venkat,

      Please check out the code now I have made some changes and now the query exception doesn’t occur if the account is related to 50k records.

      Thank You.

Leave a Reply

Your email address will not be published. Required fields are marked *