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.
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
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
From Developer Console >> File >> New >> Apex Trigger
EmployeeSizeTrigger2.apxt [Apex Class Trigger]
TRIGGER EmployeeSizeTrigger2 ON parentObjTrigger__c (BEFORE INSERT, BEFORE UPDATE, after INSERT, after UPDATE, BEFORE DELETE, after DELETE) {
List<parentObjTrigger__c> prntList= NEW List<parentObjTrigger__c>();
Set<Id> setOldId= NEW Set<Id>();
List<childObjTrigger__c> childListNew= NEW List<childObjTrigger__c>();
List<childObjTrigger__c> childList= NEW List<childObjTrigger__c>();
Set<Id> childSetId = NEW Set<Id>();
IF(TRIGGER.isBefore){
system.debug('Event before trigger');
IF(TRIGGER.isDelete){
prntList=TRIGGER.old;
prntList = [SELECT Id, Name, Status__c, LastModifiedDate__c, (SELECT Id, Status__c, LastModifiedDate FROM childObjTriggers__r) FROM parentObjTrigger__c WHERE Id=:TRIGGER.old];
system.debug('prntListOld' + prntList);
FOR(parentObjTrigger__c oldList: prntList){
FOR(childObjTrigger__c childList: oldList.childObjTriggers__r){
system.debug('childList ' + childList);
setOldId.add(childList.Id);
}
}
system.debug('setOldId## ' + setOldId );
List<childObjTrigger__c> childId=[SELECT Id, Name FROM childObjTrigger__c WHERE Id IN:setOldId];
DELETE childId;
}
}ELSE IF(TRIGGER.isAfter){
system.debug('Event after trigger');
DECIMAL empVal;
IF(TRIGGER.isDelete){
system.debug('setOldId## ' + setOldId );
}
ELSE IF(TRIGGER.isInsert){
prntList=TRIGGER.new;
FOR(parentObjTrigger__c prntNew:prntList){
empVal = prntNew.Employee__c;
}
FOR(INTEGER i=0; i<empVal; i++){
FOR(parentObjTrigger__c newRow:prntList){
childObjTrigger__c childItem = NEW childObjTrigger__c();
childItem.EmployeeName__c='Employee Name ' + i;
childItem.childLookup__c= newRow.Id;
childList.add(childItem);
}
}
INSERT childList;
}
ELSE IF(TRIGGER.isUpdate){
prntList=TRIGGER.new;
system.debug('trigger is updated');
List<childObjTrigger__c> childObjRelList = [SELECT Id, Status__c, LastModifiedDate FROM childObjTrigger__c WHERE childLookup__c=:prntList[0].Id];
FOR(parentObjTrigger__c prntNew:prntList){
empVal = prntNew.Employee__c;
}
FOR(parentObjTrigger__c updatePtr:prntList){
FOR(childObjTrigger__c childItemRel:childObjRelList){
system.debug('childItemRel ' + childItemRel);
childSetId.add(childItemRel.Id);
}
}
system.debug('empVal Before ' + empVal);
IF(empVal > childSetId.size()){
empVal = empVal-childSetId.size();
system.debug('empVal After ' + empVal);
FOR(INTEGER i=0; i<empVal; i++){
system.debug('empValAA ' + empVal + i);
FOR(parentObjTrigger__c updatePtr2:prntList){
childObjTrigger__c childItem2 = NEW childObjTrigger__c();
childItem2.EmployeeName__c='childSetEmp ' + i;
childItem2.childLookup__c= updatePtr2.Id;
childListNew.add(childItem2);
}
}
system.debug('childListNew 2# ' + childListNew );
upsert childListNew;
}ELSE{
Set<Id> resId = NEW Set<Id>();
system.debug('empVal$$ ' + empVal);
List<childObjTrigger__c> childObj = NEW List<childObjTrigger__c>();
List<childObjTrigger__c> childObjNullVal = NEW List<childObjTrigger__c>();
FOR(parentObjTrigger__c parentRelList:prntList){
FOR(childObjTrigger__c childItemRel:childObjRelList){
system.debug('childItemRel1 ' + childItemRel);
resId.add(childItemRel.Id);
childObj.add(childItemRel);
}
}
empVal = resId.size() - empVal;
system.debug('empVal New val ' + empVal);
FOR(INTEGER i=0; i<empVal; i++){
system.debug('empVal Loop Val ' + i);
childObj[i].childLookup__c=NULL;
childObjNullVal.add(childObj[i]);
}
UPDATE childObjNullVal;
system.debug('childObjNullVal ' + childObjNullVal);
system.debug('childObj # ' + childObj);
system.debug('resId #1 ' + resId);
system.debug('childObj$ ' + childObj);
}
}
}
}
Further post that would you like to learn in Salesforce
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
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 |