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';

      return Database.getQueryLocator(query);

     } Global void execute(Database.BatchableContext BC,  


       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

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

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.

  • i got error like variable doesnot exist stagechanged__c but have that date field on opportunity
    – subhash
    Dec 8 '17 at 11:39
  • See updated comment. Apologies.
    – TSmith
    Dec 8 '17 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
    Dec 8 '17 at 11:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.