How to get the that changed field on a record?

259    Asked by AugustinaFuentes in Salesforce , Asked on Feb 24, 2023

 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?

Answered by Claudine Tippins

I think that what you need is something like the method below to get the that changed field, 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 ();
    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 bumping up if it helped you.


Your Answer

Interviews

Parent Categories