Skip to content
  • Surfmyindia |
  • Lifedreamguide |
  • w3webmart |
  • Overstockphoto |
  • News24globalworld |
  • News24classictimes |
  • Incriediableindia |
  • TechW3web |
  • W3Force ..
w3web.net
Sign Up to Get Free Code Access → |
  • Home
  • Tutorial
    • Lightning Component
    • Salesforce LWC
    • Salesforce Integration
    • Visualforce
    • Trigger
    • JQuery
  • Get Free Courses
  • Integration
  • Aura Comp
  • Salesforce LWC
  • Visualforce
  • Trigger
  • JQuery
  • React Js
  • More
    • About Us
    • Contact Us
    • Sitemap
    • Course Pricing
    • Blog
    • Gallery
    • Most Popular Articles
    • Download E-Book
    • YouTube Channel


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

February 12, 2026 by Vijay Kumar
84 views

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:

👉 Download Free Ebook →

👉 Get Complementary →

right side banner -- www.w3webmart.com
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

  1.  
  2.    TRIGGER ContactLeadSourceCountTrigger ON Contact
  3. (after INSERT, after UPDATE, after DELETE, after undelete) {
  4.  
  5.     Set<Id> accountIds = NEW Set<Id>();
  6.  
  7.     // Collect AccountIds
  8.     IF(TRIGGER.isInsert || TRIGGER.isUpdate || TRIGGER.isUndelete){
  9.         FOR(Contact con : TRIGGER.new){
  10.             IF(con.AccountId != NULL){
  11.                 accountIds.add(con.AccountId);
  12.             }
  13.         }
  14.     }
  15.  
  16.     IF(TRIGGER.isDelete){
  17.         FOR(Contact con : TRIGGER.old){
  18.             IF(con.AccountId != NULL){
  19.                 accountIds.add(con.AccountId);
  20.             }
  21.         }
  22.     }
  23.  
  24.     IF(accountIds.isEmpty()){
  25.         RETURN;
  26.     }
  27.  
  28.     // CREATE separate maps FOR each LeadSource
  29.     Map<Id, Integer> webMap = NEW Map<Id, Integer>();
  30.     Map<Id, Integer> phoneMap = NEW Map<Id, Integer>();
  31.     Map<Id, Integer> partnerMap = NEW Map<Id, Integer>();
  32.     Map<Id, Integer> advertisementMap = NEW Map<Id, Integer>();
  33.  
  34.     // Aggregate Query
  35.     List<AggregateResult> results = [
  36.         SELECT AccountId, LeadSource, COUNT(Id) totalCount
  37.         FROM Contact
  38.         WHERE AccountId IN :accountIds
  39.         AND LeadSource IN ('Web','Phone Inquiry','Partner Referral','Advertisement')
  40.         GROUP BY AccountId, LeadSource
  41.     ];
  42.  
  43.     // Store counts IN respective maps
  44.     FOR(AggregateResult ar : results){
  45.  
  46.         Id accId = (Id) ar.get('AccountId');
  47.         String SOURCE = (String) ar.get('LeadSource');
  48.         INTEGER countValue = (INTEGER) ar.get('totalCount');
  49.  
  50.         IF(SOURCE == 'Web'){
  51.             webMap.put(accId, countValue);
  52.         }
  53.         ELSE IF(SOURCE == 'Phone Inquiry'){
  54.             phoneMap.put(accId, countValue);
  55.         }
  56.         ELSE IF(SOURCE == 'Partner Referral'){
  57.             partnerMap.put(accId, countValue);
  58.         }
  59.         ELSE IF(SOURCE == 'Advertisement'){
  60.             advertisementMap.put(accId, countValue);
  61.         }
  62.     }
  63.  
  64.     List<Account> accountList = NEW List<Account>();
  65.  
  66.     // UPDATE Accounts
  67.     FOR(Id accId : accountIds){
  68.  
  69.         Account acc = NEW Account();
  70.         acc.Id = accId;
  71.  
  72.         acc.Web_Contacts__c = webMap.containsKey(accId) ? webMap.get(accId) : 0;
  73.         acc.Phone_Contacts__c = phoneMap.containsKey(accId) ? phoneMap.get(accId) : 0;
  74.         acc.Partner_Contacts__c = partnerMap.containsKey(accId) ? partnerMap.get(accId) : 0;
  75.         acc.Advertisement_Contacts__c = advertisementMap.containsKey(accId) ? advertisementMap.get(accId) : 0;
  76.  
  77.         accountList.add(acc);
  78.     }
  79.  
  80.     IF(!accountList.isEmpty()){
  81.         UPDATE accountList;
  82.     }
  83. }

 

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

 

 

FAQ (Frequently Asked Questions)

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

  • Whenever an Account’s Phone or Email is updated, Update all related Contacts with the same Phone & Email Use @future method (asynchronous processing) in SalesforceWhenever an Account’s Phone or Email is updated, Update all related Contacts with the same Phone & Email Use @future method (asynchronous processing) in Salesforce
  • Apex Trigger Whenever Opportunity is: Inserted/Updated/Deleted/Undeleted We need to: Calculate total Amount of all Opportunities Where StageName = ‘Closed Won’ And update it on AccountApex Trigger Whenever Opportunity is: Inserted/Updated/Deleted/Undeleted We need to: Calculate total Amount of all Opportunities Where StageName = ‘Closed Won’ And update it on Account
  • 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.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.
  • Apex trigger on Account to avoid creation of duplicate record if the account with same phone exists in the system in Salesforce | Write a trigger on Account to Prevent the user to create duplicate Account based on Phone if Phone number is already exist in SalesforceApex trigger on Account to avoid creation of duplicate record if the account with same phone exists in the system in Salesforce | Write a trigger on Account to Prevent the user to create duplicate Account based on Phone if Phone number is already exist in Salesforce
  • Write apex trigger to update the related Child__c Phone whenever Parent__c Phone is updated in SalesforceWrite apex trigger to update the related Child__c Phone whenever Parent__c Phone is updated in Salesforce
  • Apex Trigger to update Account phone from Contact Phone based on lookup relationship in Salesforce | Update the related Account Phone if Contact Record is Created in SalesforceApex Trigger to update Account phone from Contact Phone based on lookup relationship in Salesforce | Update the related Account Phone if Contact Record is Created in Salesforce
  • Write a trigger on Account Whenever New Account Record is created, then needs to create associated Contact Record Automatically with Account name as Contact LastName and Account Phone as Contact Phone in Salesforce | Apex Trigger Create Related Contact whenever new Account is created in SalesforceWrite a trigger on Account Whenever New Account Record is created, then needs to create associated Contact Record Automatically with Account name as Contact LastName and Account Phone as Contact Phone in Salesforce | Apex Trigger Create Related Contact whenever new Account is created in Salesforce
  • Apex Trigger Whenever Case is: Inserted/Updated/Deleted/Undeleted We need to count Cases based on Priority: High, Medium, Low And update counts on AccountApex Trigger Whenever Case is: Inserted/Updated/Deleted/Undeleted We need to count Cases based on Priority: High, Medium, Low And update counts on Account

👉 Get Complementary →

right side banner -- www.w3webmart.com
 
  
👉 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



Vijay Kumar

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

Categories Trigger, Tutorial Tags Get count of contacts on account salesforce, Roll up summary trigger on Contact to Account, Trigger on account and contact in salesforce, Whenever opportunity created update account object with total opportunities and total amount, Write a trigger on Account to create no of contacts based on a field value from Account record, Write a trigger that updates a field in a parent account record when a Contact record is updated, write a trigger to update contact when accounts phone changed, Write a trigger which updates location of opportunity based on ownerid if user location is updated
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.
Apex Trigger Whenever Opportunity is Inserted/Updated/Deleted/Undeleted We need to count how many Opportunities have: StageName = ‘Closed Won’ And update that count on Account.

Archives →

Categories →

  • Agentforce (4)
  • Blog (4)
  • More (7)
  • Tutorial (326)
    • Formula Field (1)
    • JQuery (13)
    • Lightning Component (60)
    • React Js (15)
    • Salesforce Integration (41)
    • Salesforce LWC (115)
    • Trigger (57)
    • Validation Rule (9)
    • Visualforce (16)
  • Uncategorized (4)

Global Visitors →

Popular Posts →

  • Salesforce REST API Integration Using Postman – Complete Tutorial | Understanding How to Call Salesforce Web Service | Salesforce REST API: A Step-by-Step Guide | Tech W3Web 3.33 views per day
  • add page header or footer into a visualforce -- w3web.net How to make header and footer fixed and repeat on Visualforce page rendered as PDF in Salesforce | How to add header and footer in Visualforce page rendered as PDF in Salesforce 3 views per day
  • trigger to create account Automatically whenever contact is is created -- w3web.net Apex Trigger on Contact to Create Account Automatically and map to related account Id to Contact Whenever New Contact is Created in Salesforce | trigger to create account automatically whenever contact is created in salesforce 2.50 views per day
  • create lightning datatable row actions in lwc -- w3web.net Creating a Lightning Datatable with Row Actions and Display a Modal Popup on Click View Icon Button in Salesforce Lightning Web Component – LWC | how to create lightning datatable row actions in lwc 2.33 views per day
  • create form fields horizontally in lwc -- w3web.net How to align lightning-input form elements horizontally uses of slds-form-element_horizontal css and lightning-card tag in Lightning Web Component – LWC | How to create horizontal input label using slds-form-element/slds-form-element_horizontal... 2.33 views per day
  • Do not allow delete Account, if any of related Contact associated with Account in Salesforce | Prevent the deletion of Account which have related contact through apex trigger in Salesforce 2.33 views per day
  • display different types of toast message in lwc -- w3web.net How to display different types of custom toast message as Error, Success, Info and warning toast notifications on click button, uses of ShowToastEvent property in Salesforce Lightning Web Component — LWC | display custom toast notification in... 2 views per day
  • change stateful button value in lwc -- w3web.net How to change the state of button value as ‘follow/unfollow’ or ‘like/dislike’ through onclick handler method uses of ‘lightning-button-stateful’ tag elements in Salesforce LWC (Lightning Web Component) | How to c... 2 views per day

Get Free Courses →

right side banner -- www.surfmyindia.com
right side banner -- overstockphoto.blogspot.com

Join Our Newsletter →

Loading
right side banner -- www.lifedreamguide.com

Recent Posts →

  • Create a hand-on example as pass input value from parent to child component through PubSub Model LWC in Salesforce
  • How to pass input value from parent to child component through LMS method in Salesforce | Hand-on example as pass input value from parent to child component through Lightning Message Service (LMS) in Salesforce
  • Apex Trigger Whenever Case is: Inserted/Updated/Deleted/Undeleted We need to count Cases based on Priority: High, Medium, Low And update counts on Account
right side banner -- www.w3webmart.com


header banner -- www.overstockphoto.blogspot.com
  • Follow Me →
➡ : Facebook
➡ : Twitter
➡ : Linkedin
➡ : Instagram
➡ : Reddit
➡ : Forcetalks
➡ : Pinterest
➡ : Github
➡ : Medium
➡ : Tumblr
➡ : Telegram
 

🧩 Get Free Courses

👉 Get Complementary →

right side banner -- www.w3webmart.com
header banner -- www.overstockphoto.blogspot.com

Recent Posts →

  • Create a hand-on example as pass input value from parent to child component through PubSub Model LWC in Salesforce
  • How to pass input value from parent to child component through LMS method in Salesforce | Hand-on example as pass input value from parent to child component through Lightning Message Service (LMS) in Salesforce
  • Apex Trigger Whenever Case is: Inserted/Updated/Deleted/Undeleted We need to count Cases based on Priority: High, Medium, Low And update counts on Account
  • Apex Trigger Whenever Opportunity is: Inserted/Updated/Deleted/Undeleted We need to: Calculate total Amount of all Opportunities Where StageName = ‘Closed Won’ And update it on Account
  • Apex Trigger Whenever Opportunity is Inserted/Updated/Deleted/Undeleted We need to count how many Opportunities have: StageName = ‘Closed Won’ And update that count on Account.
  • 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.
header banner -- www.lifedreamguide.com

Popular Posts →

  • How to pass input value from parent to child component through LMS method in Salesforce | Hand-on example as pass input value from parent to child component through Lightning Message Service (LMS) in Salesforce 7 views
  • Create a hand-on example as pass input value from parent to child component through PubSub Model LWC in Salesforce 6 views
  • How to Navigate to External Web Page in LWC – Lightning Web Component | How to use Navigation Service (NavigationMixin.Navigate) to Navigate to External Web Page in LWC 3 views
  • create lightning-card container with custom tab in lwc -- w3web.net How to create lightning-card container with custom tab functionality uses a button in the actions slot where we are opening a lightning popup inside a custom form, displaying plain text in the footer slot in Salesforce LWC | How to apply lightning-card to create stylized container around a grouping of information to display different section like Header, Body, Footer and button actions with open a popup inside form in Salesforce LWC (Lightning Web Component) 3 views
  • Surfmyindia |
  • Lifedreamguide |
  • w3webmart |
  • Overstockphoto |
  • News24classictimes |
  • TechW3web |
  • Refund Policy |
  • Delivery Policy |
  • Privacy Policy |
  • Term & Conditions
© 2026 w3web.net • Built with GeneratePress

Chat Now