Apex trigger to create and count the number of child records associated with parent object based on custom field when parent record is created/updated in Salesforce | Count the number of child record using trigger in Salesforce

3,227 views

Hey guys, today in this post we are going to learn about Apex trigger to create and count the number of child records associated with parent object based on custom field when parent record is created/updated in Salesforce.

Real time scenarios:- Write a trigger on parent object where create a custom field as Employee (Number type).

If user insert the parent record, the child record should be automatic inserted equal to the same value of employee.

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!

 

Or if user update the value of employee less then the total number of child records, in this case the child records should be exist only equal to value of employee size, rest records of child object should be automatic removed.

Files we used in this post example

EmployeeSizeTrigger2.apxt Apex Class Trigger It will be fired whenever insert or update a record on parent object

Parent Cusotm Object:- parentObjTrigger__c

Custom Field:- EmployeeName__c

Parent Object with Custom Field Trigger on parent object and updae the count of related child records with the custom field value of parent object.

Child Custom Object:- childObjTrigger__c

Custom Field:- childLookup__c : Lookup(parentObjTrigger)

Child Object with Custom Field childLookup__c : Lookup(parentObjTrigger) field it is help to communicate on parent object.

Live Example

Trigger to update parent object value -- w3web.net

 

You can download file directly from github by Click Here.

 
 

Other related post that would you like to learn in Salesforce

 

Step 1:- Apex Class Trigger : EmployeeSizeTrigger2.apxt

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 

From Developer Console >> File >> New >> Apex Trigger

EmployeeSizeTrigger2.apxt [Apex Class Trigger]

  1.    TRIGGER EmployeeSizeTrigger2 ON parentObjTrigger__c (BEFORE INSERT, BEFORE UPDATE, after INSERT, after UPDATE, BEFORE DELETE, after DELETE) {  
  2.     List<parentObjTrigger__c> prntList= NEW List<parentObjTrigger__c>();
  3.     Set<Id> setOldId= NEW Set<Id>(); 
  4.     List<childObjTrigger__c> childListNew= NEW List<childObjTrigger__c>();
  5.     List<childObjTrigger__c> childList= NEW List<childObjTrigger__c>();
  6.     Set<Id> childSetId = NEW Set<Id>();
  7.     IF(TRIGGER.isBefore){
  8.         system.debug('Event before trigger');
  9.         IF(TRIGGER.isDelete){
  10.             prntList=TRIGGER.old;
  11.             prntList = [SELECT Id, Name, Status__c, LastModifiedDate__c, (SELECT Id, Status__c, LastModifiedDate FROM childObjTriggers__r) FROM parentObjTrigger__c WHERE Id=:TRIGGER.old];
  12.             system.debug('prntListOld' + prntList);
  13.             FOR(parentObjTrigger__c oldList: prntList){               
  14.                 FOR(childObjTrigger__c childList: oldList.childObjTriggers__r){
  15.                     system.debug('childList ' + childList);
  16.                     setOldId.add(childList.Id);
  17.                 }
  18.             }
  19.             system.debug('setOldId## ' + setOldId ); 
  20.             List<childObjTrigger__c> childId=[SELECT Id, Name FROM childObjTrigger__c WHERE Id IN:setOldId];
  21.             DELETE childId;
  22.         }
  23.     }ELSE IF(TRIGGER.isAfter){
  24.         system.debug('Event after trigger');
  25.         DECIMAL empVal;
  26.         IF(TRIGGER.isDelete){
  27.             system.debug('setOldId## ' + setOldId ); 
  28.  
  29.         }
  30.         ELSE IF(TRIGGER.isInsert){
  31.             prntList=TRIGGER.new;
  32.  
  33.             FOR(parentObjTrigger__c prntNew:prntList){
  34.                 empVal = prntNew.Employee__c;
  35.             }
  36.             FOR(INTEGER i=0; i<empVal; i++){
  37.                 FOR(parentObjTrigger__c newRow:prntList){
  38.                     childObjTrigger__c childItem = NEW childObjTrigger__c();
  39.                     childItem.EmployeeName__c='Employee Name ' + i;
  40.                     childItem.childLookup__c= newRow.Id; 
  41.                     childList.add(childItem);
  42.                 }
  43.  
  44.             } 
  45.  
  46.             INSERT childList; 
  47.         }
  48.         ELSE IF(TRIGGER.isUpdate){
  49.             prntList=TRIGGER.new;
  50.             system.debug('trigger is updated');
  51.              List<childObjTrigger__c> childObjRelList = [SELECT Id, Status__c, LastModifiedDate FROM childObjTrigger__c WHERE childLookup__c=:prntList[0].Id]; 
  52.  
  53.             FOR(parentObjTrigger__c prntNew:prntList){
  54.                 empVal = prntNew.Employee__c;
  55.             }
  56.  
  57.             FOR(parentObjTrigger__c updatePtr:prntList){
  58.                 FOR(childObjTrigger__c childItemRel:childObjRelList){
  59.                     system.debug('childItemRel ' + childItemRel);
  60.  
  61.                     childSetId.add(childItemRel.Id); 
  62.                 } 
  63.             }
  64.             system.debug('empVal Before ' + empVal);
  65.             IF(empVal > childSetId.size()){
  66.                 empVal = empVal-childSetId.size();
  67.                 system.debug('empVal After ' + empVal);
  68.                 FOR(INTEGER i=0; i<empVal; i++){
  69.                     system.debug('empValAA ' + empVal + i);
  70.                     FOR(parentObjTrigger__c updatePtr2:prntList){
  71.                         childObjTrigger__c childItem2 = NEW childObjTrigger__c();
  72.                         childItem2.EmployeeName__c='childSetEmp ' + i;
  73.                         childItem2.childLookup__c= updatePtr2.Id;
  74.                         childListNew.add(childItem2);
  75.                     } 
  76.                 }
  77.                 system.debug('childListNew 2# ' + childListNew );
  78.                 upsert childListNew;
  79.  
  80.             }ELSE{
  81.                 Set<Id> resId = NEW Set<Id>();
  82.                 system.debug('empVal$$ ' + empVal);
  83.                 List<childObjTrigger__c> childObj = NEW List<childObjTrigger__c>(); 
  84.                 List<childObjTrigger__c> childObjNullVal = NEW List<childObjTrigger__c>();
  85.                 FOR(parentObjTrigger__c parentRelList:prntList){
  86.                     FOR(childObjTrigger__c childItemRel:childObjRelList){
  87.                         system.debug('childItemRel1 ' + childItemRel);                                             
  88.                         resId.add(childItemRel.Id);
  89.                         childObj.add(childItemRel);
  90.                     }
  91.  
  92.                 }
  93.  
  94.                 empVal = resId.size() - empVal;
  95.                 system.debug('empVal New val ' + empVal);
  96.  
  97.                 FOR(INTEGER i=0; i<empVal; i++){
  98.                     system.debug('empVal Loop Val ' + i);
  99.                       childObj[i].childLookup__c=NULL;
  100.                       childObjNullVal.add(childObj[i]);
  101.                 }
  102.                UPDATE childObjNullVal;
  103.                system.debug('childObjNullVal ' + childObjNullVal); 
  104.  
  105.                 system.debug('childObj # ' + childObj);
  106.                 system.debug('resId #1 ' + resId);
  107.                 system.debug('childObj$ ' + childObj);
  108.  
  109.             }
  110.  
  111.  
  112.         }
  113.  
  114.     }
  115. }

 

Apex trigger to count child records -- w3web.net

Further post that would you like to learn in Salesforce

 

 

 

FAQ (Frequently Asked Questions)

How do you handle errors in Apex class?

Apex uses the try, catch, and finally block to handle an exception. You “try” to run your code and if an exception occurs you catch it and write the code to handle it in the “catch” block. You write the code that must execute whether an exception occurs or not in the final block.

How do I run an Apex class in developer console?

Follow the steps to execute apex code in developer console. Now go to Debug=>Open execute anonymous window. Use CTRL + E shortcut to open window to execute apex code. Now click on execute button.

What is Apex test class in Salesforce?

The Apex testing framework enables you to write and execute tests for your Apex classes and triggers on the Lightning Platform. Apex unit tests ensure high quality for your Apex code and let you meet requirements for deploying Apex.

Related Topics | You May Also Like

 
Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  

Our Free Courses →

👉 Get Free Course →

📌 Salesforce Administrators

📌 Salesforce Lightning Flow Builder

📌 Salesforce Record Trigger Flow Builder

👉 Get Free Course →

📌 Aura Lightning Framework

📌 Lightning Web Component (LWC)

📌 Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment