In some cases there is a need to check if some fields were changed depending on defined criteria.

For example I want fo forbid editing fields Is_Confirmed__c and Coordinator__c on Opportunity if stage equals Confirmed and record type is Service Opportunity.

private static Map <String, Schema.SObjectField> objectFieldsMap = Schema.getGlobalDescribe().get('Opportunity').getDescribe().fields.getMap();

private static boolean validateForbidEditingEvent(Opportunity oldOpportunity, Opportunity newOpportunity) {
        Boolean showError = FALSE;
        String rtName = rtMap.get(oldOpportunity.RecordTypeId).getName();
    
        if (rtName == 'Service Opportunity' && oldOpportunity.Stage == 'Confirmed') {
            Set<String> fieldsToCheck = new Set<String> {'Is_Confirmed__c', 'Coordinator__c'};
       
            for (String fieldname : fieldsToCheck) {
                if ( oldOpportunity.get(objectFieldsMap.get(fieldname)) != (newOpportunity.get(objectFieldsMap.get(fieldname))) ) {
                    showError = TRUE;
                    //System.Debug('@@ Changed field: ' + fieldname);
                }
            }

            if(showError == true) {                
                newOpportunity.addError('You cannot change Fields: Is Confirmed and Coordinator in this stage.');
                return true;
            }
            return false;
        }
    }
}

 

   
© Paweł Woźniak