[SalesForce] Long text area field – Trigger is detecting field change even when no changes are made to the field

I have a long text area field which is on the page layout along with other fields. User is changing a picklist field but when trigger compares old and new values, long text are field is also detected as changed even when user has not made any changes to it.
In the below code if condition is satisfied, when I check old and new records using get method and passing field API Name,

for(CustomObj__c req: trigger.new)
    {
        CustomObj__c oldreq = trigger.oldMap.get(req.Id);
    String longtextareafieldAPIName = 'MyCustomField__c';
                if(req.get(longtextareafieldAPIName) != oldreq.get(longtextareafieldAPIName) )
                {
                    system.debug('changed field - ' + longtextareafieldAPIName);
                    system.debug('old value - ' + oldreq.get(longtextareafieldAPIName));
                    system.debug('new value - ' + req.get(longtextareafieldAPIName));
                }

    }

when I compare the system debug output of old and new value, they are exactly the same.
Any reason why .get method is returning different values ?

Best Answer

As mentioned in Apex Developer Guide, Use the field describe result's getMap method to return a map that represents the relationship between all the field names (keys) and the field tokens (values) for an sObject.

Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.Account.fields.getMap();

Get all the Field API Names using the keySet() method of the Map. Then Loop through the Fields and compare the Field value in Old Map and New Map.

I tried the following example on a sObject containing Long Text Area field, but could not re-produce your case. The change is detected only when there is a change in the Long Text area.

trigger BookTrigger on Book__c (after update) {
    // Get all the Book fields 
    Map<String, Schema.SObjectField> bookFieldsMap = Schema.SObjectType.Book__c.fields.getMap();
    //Get all the field API Names
    Set <String> bookAPIFieldNames = bookFieldsMap.keySet(); 
    // For each Book in the trigger
    for (sObject bookRecord : trigger.new){
        // For each field
        for(String field : bookAPIFieldNames){
            // Check whether the new value is different from old value for the same record
            if (bookRecord.get(field) != trigger.oldMap.get(bookRecord.id).get(field) ){
                System.debug(field + ' Value changed.');
            }
        }
    }
}