+ Start a Discussion
Calin Constantin BostanCalin Constantin Bostan 

Create a rule that runs every time a specific value is updated in an opportunity

Hi All,

I have a request from our business, to create a field on a custom object called Vehicle, A field that show the total values of the opportunities associated with the specific vehicle. Our in-house developer managed to do that, but with a schedule rule that runs only once/day, and the request is to show the total amount every time an amount in a opportunity is updated.

The developer created 2 different classes, one to make a sum of all values from all opportunities:
/* @date 29.09.2017 */
/* @description for update a summary field on vehicle level, which sums up the opportunity amount of the related opportunities*/
global class Opportunity_Amount_Update implements Database.Batchable<sObject>  {

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT ID FROM Vehicle__c ' );
    }
    
    global decimal STTO = 0;

    global void execute(Database.BatchableContext bc, List<Vehicle__c> scope){
        // process each batch of records
        Set<Vehicle__c> Veh = new Set<Vehicle__c>();
        List<Vehicle__c> Veh1 = new List<Vehicle__c>();
        List<Opportunity> OPP = [Select Id, GH_Vehicle__c, Amount from Opportunity WHERE GH_Vehicle__c <>'']; 
          for (Vehicle__c VEx : scope) {    
            for (Opportunity Opps1 : OPP ) {
                 if(Opps1.GH_Vehicle__c == VEx.id) {
                     STTO = STTO + Opps1.Amount;
                 }
            }
            VEx.Opportunity_amount__c = STTO;
            Veh.add(VEx);
            STTO = 0;
         }
        Veh1.addall(Veh);
        update Veh1;
    }    

    global void finish(Database.BatchableContext bc){
    }    
}

And another one as a scheduler:
global class Opportunity_Amount_Update_scheduler implements Schedulable {
    global void execute(SchedulableContext ctx) {
        Opportunity_Amount_Update OA = new Opportunity_Amount_Update();
        DataBase.executeBatch(OA);
    }
}

Ans as I mentionated abowe, we need the first class (Opportunity_Amount_Update) to run every time the value of an opportunity changes.
Can you please help me with this, if it can be made like that?

Thank You
Calin B
Best Answer chosen by Calin Constantin Bostan
Shawn Reichner 29Shawn Reichner 29
You can simply delete the scheduled job, keep the class you have listed above and create a very simple trigger to run on before insert and before update to call your class and method.  This will then tun every time a record is inserted or updated.  

You may have to re-write this as it looks liek this class is starting on the parent level (Vehicle) where I would do the roll ups from the Opportunity Object so that when one is inserted for a vehicle or updated then the Vehicle record would be updated to reflect all Opps. 

Hope that helps,

Shawn