Apex Trigger Whenever Contact is Inserted/Updated/Deleted/Undeleted We need to count Contacts based on LeadSource and update Account, LeadSource values: Web, Phone Inquiry, Partner Referral, Advertisement
Step 1 Create Fields on Account
Create 4 Number fields:
| Field Label | API Name |
|---|---|
| Web Contacts | Web_Contacts__c |
| Phone Contacts | Phone_Contacts__c |
| Partner Contacts | Partner_Contacts__c |
| Advertisement Contacts | Advertisement_Contacts__c |
Data Type → Number (0 decimal)
Logic (Same Pattern as Country Example)
- Collect AccountIds
- Run ONE Aggregate SOQL
- Store results in separate Maps
- Update Account
Step 2 Contact Trigger (After Update): ContactLeadSourceCountTrigger.apxt
TRIGGER ContactLeadSourceCountTrigger ON Contact
(after INSERT, after UPDATE, after DELETE, after undelete) {
Set<Id> accountIds = NEW Set<Id>();
// Collect AccountIdsIF(TRIGGER.isInsert || TRIGGER.isUpdate || TRIGGER.isUndelete){
FOR(Contact con : TRIGGER.new){
IF(con.AccountId != NULL){
accountIds.add(con.AccountId);
}}}IF(TRIGGER.isDelete){
FOR(Contact con : TRIGGER.old){
IF(con.AccountId != NULL){
accountIds.add(con.AccountId);
}}}IF(accountIds.isEmpty()){
RETURN;}// CREATE separate maps FOR each LeadSource
Map<Id, Integer> webMap = NEW Map<Id, Integer>();
Map<Id, Integer> phoneMap = NEW Map<Id, Integer>();
Map<Id, Integer> partnerMap = NEW Map<Id, Integer>();
Map<Id, Integer> advertisementMap = NEW Map<Id, Integer>();
// Aggregate QueryList<AggregateResult> results = [
SELECT AccountId, LeadSource, COUNT(Id) totalCount
FROM ContactWHERE AccountId IN :accountIds
AND LeadSource IN ('Web','Phone Inquiry','Partner Referral','Advertisement')
GROUP BY AccountId, LeadSource
];// Store counts IN respective maps
FOR(AggregateResult ar : results){
Id accId = (Id) ar.get('AccountId');
String SOURCE = (String) ar.get('LeadSource');
INTEGER countValue = (INTEGER) ar.get('totalCount');
IF(SOURCE == 'Web'){
webMap.put(accId, countValue);
}ELSE IF(SOURCE == 'Phone Inquiry'){
phoneMap.put(accId, countValue);
}ELSE IF(SOURCE == 'Partner Referral'){
partnerMap.put(accId, countValue);
}ELSE IF(SOURCE == 'Advertisement'){
advertisementMap.put(accId, countValue);
}}List<Account> accountList = NEW List<Account>();
// UPDATE Accounts
FOR(Id accId : accountIds){
Account acc = NEW Account();
acc.Id = accId;
acc.Web_Contacts__c = webMap.containsKey(accId) ? webMap.get(accId) : 0;
acc.Phone_Contacts__c = phoneMap.containsKey(accId) ? phoneMap.get(accId) : 0;
acc.Partner_Contacts__c = partnerMap.containsKey(accId) ? partnerMap.get(accId) : 0;
acc.Advertisement_Contacts__c = advertisementMap.containsKey(accId) ? advertisementMap.get(accId) : 0;
accountList.add(acc);
}IF(!accountList.isEmpty()){
UPDATE accountList;}}
Why This Is Clean & Best Practice?
- Only ONE SOQL
- Uses AggregateResult
- No SOQL inside loop
- No DML inside loop
- Bulk safe (200 records)
- Beginner friendly structure
- Same pattern as your previous country trigger
How to enable AccountContactRelation in Salesforce?
To make use of AccountContactRelation in query, we first need to enable this feature from Setup menu. From Setup, enter Account Settings in the Quick Find box, then select Account Settings. Select Allow users to relate a contact to multiple accounts.
What is count() used for?
The COUNT function counts the number of cells that contain numbers, and counts numbers within the list of arguments. Use the COUNT function to get the number of entries in a number field that is in a range or array of numbers.
How many contacts will my phone hold?
There is no specific limit on the number of contacts as the memory space for Contacts is dynamically allocated. So, if the user memory is completely filled up with no space left, it might start to inhibit the contact capacity.
Related Topics | You May Also Like
|
👉 Get Free Course →
📌 Salesforce Administrators 📌 Salesforce Lightning Flow Builder 📌 Salesforce Record Trigger Flow Builder |
👉 Get Free Course → |


