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
An_jaAn_ja 

Need help to bulkify trigger - system limit exception too many SOQL queries 101

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

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

    // get list of accounts
    Set<ID> acctIds = new Set<ID>();
    for (Contact con : cons) 
    {
            acctIds.add(con.AccountId);
    }
    
    Map<ID, Contact> contactsForAccounts = new Map<ID, Contact>([select Id,
                                              	AccountId
                                              	from Contact
                                              	where AccountId IN :acctIds and Sub_Type__c 
                                              	IN ('DMD', 
                                              	'DCD')]); //

    Map<ID, Account> acctsToUpdate = new Map<ID, Account>([select Id,
                                                Active_DVA_DCD__c 
                                                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)
                conIds.add(con.Id);
        }
        if (acct.Active_DVA_DCD__c != conIds.size())
            acct.Active_DVA_DCD__c = conIds.size();
    }

    update acctsToUpdate.values();

}

 

 

 

SamuelDeRyckeSamuelDeRycke

I think it is because your trigger is "after update" and does an update statement in the end. The logical build up of your trigger looks fine to me. Can you do it on before update ?

 

ps: using the code block feature, your code would be easier to read.