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
chubsubchubsub 

Trigger Help Needed Narrow Class by Account

I have a field called Daily_Tracking_Number__c on Opportunity.  This field will track the number of opportunities that have been submitted on an Account each day.  So, the first opportunity that is created today for Client A will be 1, then for another opportunity created that day, the field will update to 2.  Then, the next day, if an opportunity is created for Client A, it will reset back to 1.  

 

Now, the part I'm struggling with is narrowing it down per Account, so if an opportunity is created for Client A today, the field will be 1, then, if an opportunity is created for Client B, the field on that Opportunity will also be 1.  And if another opportunity is created the same day for Client A, the field will equal 2, and then the same for Client B. And then it will reset again the next day.

 

The code below will update the Daily Tracking Number field correctly and will reset every day, but it doesnt narrow it down by Account like I explained above.  What it does is give the Daily Tracking Number field a number that picks up where the last Opportunity was created, regardless of the Account.

 

Any ideas on binding this code to the Account?  Thanks!

 

This is the trigger and class that I have so far:

 



1
2
3
4
5
6
trigger ManageOpportunities on Opportunity (before insert) { 

    if(Trigger.isInsert && Trigger.isBefore){
        ManageOpportunities.beforeInsert(Trigger.New); 
    }     
} //end trigger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public with sharing class ManageOpportunities {


//Tracking Numbers are reset each day, so we'll query for the current number and add to it for the optys
public static void beforeInsert(Opportunity [] optys) {

Decimal todaystrackingnumber;
//get the current number - there might not be one, so we'll query into a list

Opportunity [] todaysoptys =  [Select Id, AccountId, Daily_Tracking_Number__c from Opportunity where CreatedDate = TODAY AND Daily_Tracking_Number__c != null order by Daily_Tracking_Number__c Desc];

//if there is a case, then use the first one, since it is ordered by number
    if (todaysoptys.size() > 0) {
        todaystrackingnumber = todaysoptys[0].Daily_Tracking_Number__c + 1;
    }
    else {
        todaystrackingnumber = 1;
    }

//Now loop through the new cases and allocate a number

for (Opportunity o: optys) {
o.Daily_Tracking_Number__c = todaystrackingnumber;
todaystrackingnumber ++;
}
    
} //end before insert


} //end class