Write Apex Trigger Whenever a Contact is Inserted / Updated / Deleted, We need to Count child Contacts related to each Account Based on MailingCountry Only for these 4 countries (India, USA, England, Japan) Then store the count on Account object.
Create Custom Fields on Account
Create 4 Number fields on Account:
| Field Label | API Name |
|---|---|
| India Contacts Count | India_Contacts__c |
| USA Contacts Count | USA_Contacts__c |
| England Contacts Count | England_Contacts__c |
| Japan Contacts Count | Japan_Contacts__c |
Data Type โ Number (0 Decimal Places)
Logic Approach (Best Practice โ Bulkified)
- Use after insert
- Use after update
- Use after delete
- Use after undelete
- Collect all AccountIds
- Run Aggregate Query
- Update Account
Step 1 Account Trigger (After Update): ContactPracticeTrigger.apxt
TRIGGER AggregateResultContactPractice ON Contact (BEFORE INSERT, after INSERT, BEFORE UPDATE, after UPDATE, BEFORE DELETE, after DELETE, after undelete) {
//COUNT child Contacts related TO each Account Based ON MailingCountry ONLY FOR these 4 countries:India, USA, England, AND Japan
//THEN store the COUNT ON Account object: India_Contacts__c, USA_Contacts__c, England_Contacts__c, Japan_Contacts__c
IF(TRIGGER.isAfter){
Set<Id> accountIds = NEW Set<Id>();
IF(TRIGGER.isInsert || TRIGGER.isUpdate || TRIGGER.isUndelete){
FOR(Contact con:TRIGGER.new){
IF(con.AccountId != NULL){
accountIds.add(con.AccountId);
}}}IF(TRIGGER.isDelete || TRIGGER.isUpdate ){
FOR(Contact con2:TRIGGER.old){
IF(con2.AccountId != NULL){
accountIds.add(con2.AccountId);
}}}List<AggregateResult> agrList = [SELECT AccountId, MailingCountry, COUNT(Id) totalCount FROM Contact WHERE AccountId IN:accountIds AND MailingCountry IN ('India','USA','England','Japan') GROUP BY AccountId, MailingCountry ];
Map<Id, Integer> IndiaMap = NEW Map<Id, Integer>();
Map<Id, Integer> UsaMap = NEW Map<Id, Integer>();
Map<Id, Integer> EnglandMap = NEW Map<Id, Integer>();
Map<Id, Integer> JapanMap = NEW Map<Id, Integer>();
FOR(AggregateResult ar:agrList){
Id ids = (Id) ar.get('AccountId');
String country = (String) ar.get('MailingCountry');
INTEGER countValue = (INTEGER) ar.get('totalCount');
IF(country == 'India'){
IndiaMap.put(ids, countValue);
}ELSE IF (country == 'USA'){
UsaMap.put(ids, countValue);
}ELSE IF (country == 'England'){
EnglandMap.put(ids, countValue);
}ELSE IF (country == 'Japan'){
JapanMap.put(ids, countValue);
}}List<Account> accItem = NEW List<Account>();
FOR(Id accId:accountIds){
Account accObj = NEW Account();
accObj.India_Contacts__c = IndiaMap.get(accId);
accObj.USA_Contacts__c = UsaMap.get(accId);
accObj.England_Contacts__c = EnglandMap.get(accId);
accObj.Japan_Contacts__c = JapanMap.get(accId);
accObj.Id = accId;
accItem.add(accObj);
}IF(!accItem.isEmpty()){
UPDATE accItem;}}}
How This Works (Step-by-Step):
- Collect Account IDs from Trigger context
- Run one Aggregate SOQL query
- Group by AccountId and MailingCountry
- Store result in Map
- Update Account with country-wise count
- If no contacts โ set count = 0
Why This is Interview-Ready?:
|
๐ Up to 99% Off Courses (Coupon)
๐ฅ Use Promo Code: STANDARDOFFER๐ฅ ๐ Get Free Salesforce Course Access: www.thevijaykumar.w3web.net |
- Fully Bulkified
- Uses Aggregate Query
- Handles Insert/Update/Delete/Undelete
- No SOQL inside loop
- No DML inside loop
Further post that would you like to learn in Salesforce
Can a contact be associated with multiple accounts in Salesforce?
Enabling Account Contact Relationship access mapping feature allows your sales reps to easily track the relationships between the customers and businesses they work with. It's quick to set up and allow reps to relate a single contact record to multiple accounts.
How are contacts and accounts related in Salesforce?
The relationship rules are still simple. Every contact needs to be directly associated with an account. This is the account that appears in Account Name and is usually the company the contact is most closely associated with. Any other accounts associated with the contact represent indirect relationships.
What happens to related records when you merge accounts in Salesforce?
What happens to related records when accounts are merged? All related recordsโcontacts, opportunities, casesโare automatically transferred to the master account. Note that conflicting fields require manual selection of which data to retain.
Related Topics | You May Also Like
|
๐ Get Free Course โ
๐ Salesforce Administrators ๐ Salesforce Lightning Flow Builder ๐ Salesforce Record Trigger Flow Builder |
๐ Get Free Course โ |




