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

2,619 views


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

Real time scenarios:- Write a trigger on Account 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:- Account

Custom Field:- Employee Size (Employee__c)

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

Child Custom Object:- Contact

Custom Field:- AccountId : Lookup(Account)

Child Object with Lookup Field  

Live Example

trigger to count total child records on Parent -- w3web.net

 

You can download file directly from github by Click Here.

 
 

Other related post that would you like to learn in Salesforce

 

  • Find the below steps ▾

 

Create Apex Trigger

Step 1:- Create Apex 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 Controller]

  1.    TRIGGER employeeSizeTrigger2 ON Account (BEFORE INSERT, BEFORE UPDATE, after INSERT, after UPDATE, BEFORE DELETE, after DELETE) {
  2.  
  3.     Map<Id, List<Contact>> prntMap = NEW Map<Id, List<Contact>>();
  4.     Map<Id, Account> prntOldMap = NEW Map<Id, Account>();
  5.     Map<Id, Integer> prntMapChildNo = NEW Map<Id, Integer>(); 
  6.     Map<Id, Decimal> empValMap = NEW Map<Id, Decimal>();  
  7.     Set<Id> parentKey = prntMap.keySet();
  8.     List<List<Contact>> childKeyVal = NEW List<List<Contact>>();
  9.     List<Account> oldVal = NEW List<Account>();    
  10.     Set<Id> prntSetId = NEW Set<Id>();
  11.  
  12.     List<Contact> childObjList = NEW List<Contact>();
  13.     List<Contact> childObjNull = NEW List<Contact>();
  14.     Set<Id> childNullSetId = NEW Set<Id>();
  15.  
  16.     DECIMAL childSize;
  17.     DECIMAL empVal;
  18.     DECIMAL empValOld;
  19.  
  20.     IF(TRIGGER.isBefore){
  21.         system.debug('Event before trigger');
  22.  
  23.     }ELSE IF(TRIGGER.isAfter){
  24.         system.debug('Event after trigger');        
  25.         oldVal = TRIGGER.old;
  26.  
  27.         FOR(Account par: [SELECT Id, Name, Phone, Employee__c, (SELECT Id, Name, FirstName, LastName, AccountId FROM Contacts) FROM Account WHERE Id IN: TRIGGER.newMap.values()]){
  28.             system.debug('par$$$$$$ ' + par);
  29.             prntMap.put(par.Id, par.Contacts);
  30.             prntMapChildNo.put(par.Id, (par.Contacts).size());            
  31.         }
  32.  
  33.         system.debug('empValOld# ' +empValOld);
  34.  
  35.  
  36.         FOR(List<Contact> childObjVal:prntMap.values()){
  37.             system.debug('childObj!!!! ' + childObjVal);
  38.             childKeyVal.add(childObjVal);       
  39.         }
  40.         system.debug('childKeyVal## ' + childKeyVal);
  41.  
  42.  
  43.         List<Account> prntList = [SELECT Id, Name FROM Account WHERE Id IN:prntMap.keySet()];
  44.         FOR(Account pr1:prntList){
  45.             prntSetId.add(pr1.Id);
  46.         }
  47.         system.debug('prntSetId ' + prntSetId);
  48.         FOR(Account prantEmp:[SELECT Id,Employee__c FROM Account WHERE Id IN:prntMap.keySet()]){
  49.             empValMap.put(prantEmp.Id, prantEmp.Employee__c);
  50.             empVal = prantEmp.Employee__c;
  51.             system.debug('empValMap ' + empValMap);  
  52.  
  53.         }
  54.  
  55.         system.debug('empValMap ' + empValMap);
  56.         system.debug('empVal ' + empVal);
  57.  
  58.         List<Contact> childObjKey = NEW List<Contact>();
  59.         FOR(Contact childKey: [SELECT Id, Name, AccountId FROM Contact WHERE AccountId=:prntSetId]){
  60.             system.debug('childKey####$ ' + childKey);
  61.             childObjKey.add(childKey);
  62.  
  63.         }  
  64.  
  65.         IF(TRIGGER.isInsert){
  66.             FOR(INTEGER i=0; i<empVal; i++){
  67.                 FOR(Account prntSet:[SELECT Id, Name FROM Account WHERE Id IN:prntSetId]){
  68.                     Contact childObj = NEW Contact();
  69.                     childObj.LastName='childMap ' + i;
  70.                     childObj.AccountId=prntSet.id;
  71.                     childObjList.add(childObj);
  72.                 } 
  73.  
  74.             } 
  75.             system.debug('childObjList ' + childObjList);
  76.             INSERT childObjList;
  77.  
  78.         }ELSE IF(TRIGGER.isUpdate){  
  79.             FOR(Account parOld: oldVal){
  80.                 empValOld = parOld.Employee__c;
  81.             }
  82.  
  83.             IF(empVal !=empValOld){ 
  84.                 FOR(INTEGER intNo:prntMapChildNo.values()){
  85.                     system.debug('intNo@@ ' + intNo );
  86.                     childSize = intNo;
  87.                 }
  88.                 system.debug('childSize ' + childSize);
  89.                 IF(empVal > childSize){
  90.                     empVal = empVal - childSize;
  91.                     FOR(INTEGER i=0; i<empVal; i++){
  92.                         FOR(Account prntSet1:[SELECT Id, Name FROM Account WHERE Id IN:prntSetId]){  
  93.                             Contact childObj2 = NEW Contact();
  94.                             childObj2.LastName='update child ' + i;
  95.                             childObj2.AccountId=prntSet1.Id;
  96.                             childObjKey.add(childObj2); 
  97.                         }   
  98.                     }
  99.  
  100.                     upsert childObjKey;
  101.  
  102.                 }ELSE{
  103.                     empVal = childSize - empVal;
  104.                     system.debug('empVal $$$ ' + empVal );
  105.  
  106.                     FOR(INTEGER i=0; i<empVal; i++){
  107.                         childObjKey[i].AccountId=NULL;
  108.                         childObjNull.add(childObjKey[i]);
  109.                     }
  110.  
  111.                     UPDATE childObjNull;
  112.  
  113.                     FOR(Contact childSet:childObjNull){
  114.                         childNullSetId.add(childSet.Id);
  115.                     }
  116.                     system.debug('childNullSetId## ' + childNullSetId);
  117.                     List<Contact> deleteNull = [SELECT Id FROM Contact WHERE ID IN:childNullSetId];
  118.                     DELETE deleteNull;
  119.                 }
  120.  
  121.             }  
  122.  
  123.         } 
  124.  
  125.  
  126.     }
  127.  
  128.  
  129.  
  130. }

Further post that would you like to learn in Salesforce

 

 

 

FAQ (Frequently Asked Questions)

How many records can trigger handle?

When more than 200 records need to be triggered, Salesforce runs the trigger in chunks of 200. So, if 1000 records are updating, Salesforce runs the trigger 5 times on 200 records each time

Can we have roll up summary fields in case of parent/child relationship?

Yes, we can create Roll up Summary field on parent object only with master detail relation between objects.

How many records will execute in trigger in one execution?

Triggers execute on batches of 200 records at a time. So if 400 records cause a trigger to fire, the trigger fires twice, once for each 200 records. For this reason, you don't get the benefit of SOQL for loop record batching in triggers, because triggers batch up records as well.

 
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