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
JosephTJosephT 

Bulkify Case Trigger.

I have a case trigger to count the number of related solutions but, I am receiving a SOQL number of quiries error on an import via data loader.  Therefore, I appear to have an issue with bulkifiying this trigger;

Here is my Trigger;

trigger NumberOfSolutions on case(before update) {
if(Trigger.isUpdate)
{
List<Case> objCase= new List<Case>();
for(Case c:Trigger.New)
{
Integer intNum = 0;
intNum =[select Count() from casesolution where caseID =:c.id];
c.Number_of_Solutions__c =intNum;
objCase.add(c);
}
}
}


Any help would be greatly appreciated.

Joseph
Best Answer chosen by JosephT
Bhanu MaheshBhanu Mahesh
Hi Joseph,

Refer the above links provided to bulkify the triggers.

And for your reference

trigger NumberOfSolutions on case(before update) {
        Map<Id,Integer> caseWithCaseSoltns = new Map<Id,Integer>();
        for(Case cas : [SELECT Id,(select Id from casesolutions) FROM Case where Id IN :Trigger.newMap.keySet()]){
            caseWithCaseSoltns.put(cas.Id,cas.casesolutions.size());    
        }
        
        for(Case c:Trigger.New){
            c.Number_of_Solutions__c = caseWithCaseSoltns.get(c.Id);
        }
}

Regards,
Bhanu Mahesh

All Answers

rivereridanusrivereridanus
I ran into this issue recently. Ended up uploading 25k records in batches of 100 as a result. There is a good Best Practices article here though that gives an example similar to yours: https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_bestpract.htm
Mathew Andresen 5Mathew Andresen 5
Trailhead also has a bit longer example of how to properly strucutre your bulk triggers

https://developer.salesforce.com/trailhead/force_com_programmatic_beginner/apex_triggers/apex_triggers_bulk
 
ra811.3921220580267847E12ra811.3921220580267847E12
Hi,

trigger NumberOfSolutions on case(before update) {
Integer intNum = 0;
Set<ID> ids = Trigger.newMap.keySet();
intNum=[select count() from casesolutions where caseID in :ids];

for(Case c: trigger.new)
{
c.Number_of_Solutions__c =intNum;
}

}
Bhanu MaheshBhanu Mahesh
Hi Joseph,

Refer the above links provided to bulkify the triggers.

And for your reference

trigger NumberOfSolutions on case(before update) {
        Map<Id,Integer> caseWithCaseSoltns = new Map<Id,Integer>();
        for(Case cas : [SELECT Id,(select Id from casesolutions) FROM Case where Id IN :Trigger.newMap.keySet()]){
            caseWithCaseSoltns.put(cas.Id,cas.casesolutions.size());    
        }
        
        for(Case c:Trigger.New){
            c.Number_of_Solutions__c = caseWithCaseSoltns.get(c.Id);
        }
}

Regards,
Bhanu Mahesh
This was selected as the best answer
JosephTJosephT
Thank you all for your assistance and feedback.  Works like a charm now!

Joseph