Get the changed fields on a record?

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.

Tags:

Apex