Get the changed fields on a record?

Is there a quick/scalable/reliable way to get a list of the fields that changed before an update is made to a record? I know i get the bulk (maybe all even) in a before update trigger on the record, but I’m not sure if that would get all them?

Oder of Execution

Answer

I think that what you need is something like the method below, you can create a list of Schema.sObjectField to include/exclude certain fields.

In your trigger just call this method with the record Id.

public Schema.sObjectField[] getChangedFields(ID recordId, Schema.sObjectField[] fieldList) {
    Schema.sObjectField[] changedFields = new list<Schema.sObjectField> ();
    SObject o1 = Trigger.oldMap.get(recordId);
    SObject o2 = Trigger.newMap.get(recordId);

    for (Schema.sObjectField field : fieldList) {
        Object v1 = o1.get(field);
        Object v2 = o2.get(field);
        if (didFieldChange(v1, v2)) {
            changedFields.add(field);
        }
    }
    return changedFields;
}

private static Boolean didFieldChange(Object v1, Object v2) {
    if (v1 == null && v2 == null) {
        return false;
    }
    if (v1 != v2) {
        return true;
    }
    return false;
}

Please mark this answer as accepted if this works for you and for the other readers bump up if it helped you.

Attribution
Source : Link , Question Author : PartOfTheOhana , Answer Author : Henk3000

Leave a Comment