0

I'm trying to update a custom field on opportunity 'stagechanged__c' field (Date-datatype) when the standard stage changed from Prospecting to Qualification.

how to update date on custom field "stagechanged__c" field when standard stage field changes.

this is my batchjob :

        Global class OpportunityStageChanges implements 
       Database.Batchable<sObject> {


       Global Database.QueryLocator start(Database.BatchableContext BC) {

    String query = 'Select Id,Name,Amount,(Select ID, OldValue, NewValue 
    from OpportunityFieldHistory)from Opportunity';
    System.debug(query);

      return Database.getQueryLocator(query);

     } Global void execute(Database.BatchableContext BC,  

         List<Opportunity> 

       scope) {

         for(Opportunity opp : scope) {


        for(OpportunityFieldHistory opfh : opp.OpportunityFieldHistory) {
          system.debug(opfh.oldValue+'----'+opfh.NewValue );
        if(opfh.oldvalue == 'prospecting' && opfh.newvalue == 'Qualification'){

            //how to update the stagechanged__c custom field
        }

    }
}

}

      Global void finish(Database.BatchableContext BC) {}

     }   

how to update the stagechanged field ?

Thanks In Advance, Sekhar

3
  • Why do you need batch here. You just need a trigger. Commented Dec 8, 2017 at 11:17
  • yes you are right and this is for another purpose for historical data
    – subhash
    Commented Dec 8, 2017 at 11:22
  • could you please suggest trigger for that
    – subhash
    Commented Dec 8, 2017 at 11:22

1 Answer 1

1

For this scenario, a Batch class is over-engineering your problem. A trigger would be ideal.

trigger OnOpportunityAfter on Opportunity (before update) {

    for(Id oppId : Trigger.newMap.keySet()) {
        if(Trigger.oldMap.get(oppId).StageName == 'Prospecting' && Trigger.newMap.get(oppId).StageName == 'Qualification' ) {
            Trigger.newMap.get(oppId).stagechanged__c = Date.today();
        }
    }
}

I'm not sure what date you want to use in your custom field.

3
  • i got error like variable doesnot exist stagechanged__c but have that date field on opportunity
    – subhash
    Commented Dec 8, 2017 at 11:39
  • See updated comment. Apologies.
    – TSmith
    Commented Dec 8, 2017 at 11:45
  • I tried but having some confusion at logic if you don't mine i need the same requiremt in batchjob also just update the above batch as required please?
    – subhash
    Commented Dec 8, 2017 at 11:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .