0

I am trying to update the standard field of opportunity if custom field gets changed .. Here is my code for the same .. i want to run this in user mode o i am writtng class with sharing

public with sharing class UpdateOwner {

    public static void UpdateOppty(List<Opportunity> listOpportunity) {
        list <Opportunity> OpptyList = [SELECT Id,Name,Opportunity_Owner__c,OwnerId FROM Opportunity limit 200];
            for(Opportunity Opp : OpptyList) {
                if(opp.Owner__c !=null ){
                    Opp.OwnerId = opp.Opportunity_Owner__c;              
                    OpptyList.add(Opp);           
                }
            }
        update OpptyList;
    }
}

Trigger

trigger Updateoppty on Opportunity(before insert, before update) {
    if( Trigger.isInsert ) {
        if(Trigger.isBefore) {
            UpdateOwner.Updateopptyowner(Trigger.New); 
        }
    }
}

i am not sure how i can check if field is changed in apex class .. can someone please help me where i should add the logic for ischanged and what it should be

0

To check if a field has changed in a trigger, you must use the Trigger.old list to compare with the Trigger.New. Pass it to the updateopptyowner as a param and then, do something like:

if(newOpportunity.Owner__c != oldOpportunity.Owner__c)
    // logic when Owner__c field has changed

For more information check the Trigger Context Variables in the Apex Developer Guide.

0

As per your trigger code, Updateopptyowner method is called in before insert event. Your code should be look like this. Your class code is also not upto the salesforce best practice. You should not do update on the same record from trigger. Your logic can be handled in before update method.

Trigger

trigger Updateoppty on Opportunity(before insert, before update) {
    /*if( Trigger.isInsert ) {
        if(Trigger.isBefore) {
           // UpdateOwner.Updateopptyowner(Trigger.New); 
        }
    }*/
    if(Trigger.isBefore) {
       if(trigger.isInsert){

       }
       if(trigger.isUpdate){
            UpdateOwner.Updateopptyowner(Trigger.New,Trigger.oldMap); 
       }
    }

}

Class

public with sharing class UpdateOwner {

    public static void UpdateOppty(List<Opportunity> listOpportunity,Map<Id,Opportunity> oldMap) {

            for(Opportunity Opp : listOpportunity) {
                if(opp.Owner__c !=null && opp.Owner__c != oldMap.get(Opp.id).Owner__c ){
                    Opp.OwnerId = opp.Opportunity_Owner__c;              

                }
            }

    }
}

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.