function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
priya bhawna shettypriya bhawna shetty 

trigger related issue with account and contact

hi friends

i got this requirement.

please help

In Account object i created one custom field called " COUNT" so the question is ,whenever i created a contact related to that account ,COUNT custom field has to show the number,how many contacts has been created so far....

one important thing is ,pls consider all events in before insert,after update and delete also come into the existence...

how do i write trigger for this..


Saikishore Reddy AengareddySaikishore Reddy Aengareddy

/* Provide summary of Number of Contacts on Account record */ 

trigger ContactSumTrigger on Contact (after delete, after insert, after undelete, 
after update) {

    Contact[] cons;
    if (Trigger.isDelete) 
        cons = Trigger.old;
        cons =;

    // get list of accounts
    Set<ID> acctIds = new Set<ID>();
    for (Contact con : cons) {
    Map<ID, Contact> contactsForAccounts = new Map<ID, Contact>([select Id
                                                            from Contact
                                                            where AccountId in :acctIds]);

    Map<ID, Account> acctsToUpdate = new Map<ID, Account>([select Id
                                                                  from Account
                                                                  where Id in :acctIds]);
    for (Account acct : acctsToUpdate.values()) {
        Set<ID> conIds = new Set<ID>();
        for (Contact con : contactsForAccounts.values()) {
            if (con.AccountId == acct.Id)
        if (acct.Number_of_Contacts__c != conIds.size())
            acct.Number_of_Contacts__c = conIds.size();

    update acctsToUpdate.values();


Afzal MohammadAfzal Mohammad

You can create a roll-up summary field on Account. This field can get you the Count of related contacts.


Hope that helps.