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
Jay PollackJay Pollack 

Help With Batch Apex

I have a trigger that runs on the User object that updates many Cases in bulk depending on if the User exists in one of several fields on the Case. I run into issues when trying to run this on multiple User records at once, if the # of Cases exceeds 10,000 (due to SF governor limits). I'd like to break this out and use batch Apex - but I'm not sure how I convert this trigger into Batch Apex.

 

Here is the trigger code. I just need some help getting started on breaking this out into Batch. thanks!

 

trigger UpdatePTOonCase on User (after update) {

// this trigger updates the NSR PTO fields on Enterprise Cases based on changes to the NSR flag on the User record.

Set userIds = new Set();

List users = Trigger.new;

 

//list to hold cases that will need to be updated

 List casesToUpdate = new List();

 

 //gather all user ids in the update in a set

for (User u : users) {

userids.add(u.id); }

 

 // grab all open cases where this users is one of the related nsr's and place in map

Map cMap = new Map([SELECT id, nsr_lookup__c, BI_nsr_lookup__c, Tech_nsr_lookup__c, Time_nsr_lookup__c, Talent_nsr_lookup__c FROM Case WHERE isClosed = false AND (nsr_lookup__c in: userids OR BI_NSR_Lookup__c in: userids OR Tech_nsr_lookup__c in: userids OR Talent_nsr_lookup__c in: userids OR Time_nsr_lookup__c in: userids)]);

 

//create list of cases List cases

List = cmap.values();

 

//create set of case id's

Set caseids = cMap.keyset();

 

for (User u : users) {

User old = trigger.oldMap.get(u.id);

 

 if (old.PTO__c != u.PTO__c) {

 

 //loop through Case list and add case id's

for (Case c :casesList) {

 

 if (c.nsr_lookup__c == u.id) {

//set NSR PTO Field on Case

c.nsr_pto__c = u.PTO__c; }

 

 if (c.BI_nsr_lookup__c == u.id) {

//set NSR PTO Field on Case

c.BI_nsr_pto__c = u.PTO__c; }

 

if (c.Tech_nsr_lookup__c == u.id) {

//set NSR PTO Field on Case

 c.Tech_nsr_pto__c = u.PTO__c; }

 

 if (c.Time_nsr_lookup__c == u.id) {

 //set NSR PTO Field on Case

c.Time_nsr_pto__c = u.PTO__c; }

 

 if (c.Talent_nsr_lookup__c == u.id) {

 //set NSR PTO Field on Case

c.Talent_nsr_pto__c = u.PTO__c; }

 

casesToUpdate.add(c); } } }

 

//call method to prevent case triggers from firing

 PreventRecursive.setUpdatedFromUser ();

 

update casesToUpdate ; }

boBNunnyboBNunny

You most certainly can use a Batch job to do this.  But make sure that you use a QueryLocator against the object you will be updating (Case), and that you do not have any triggers on Case that call a Future method.

 

Another way I've found to do this is to get the first 9900 rows and do it your way.  THEN see if there are more rows left to handle.  If so, do them in a method with @FUTURE.  It effectively doubles your limit.