How to assign values to Schema.sobjectField[]?

532    Asked by bruce_8968 in Salesforce , Asked on May 9, 2023

I am working on after update trigger and I want to know what fields were updated. I got a code on StackExchange which would serve my purpose : But can anyone please help me on how to assign values (The fields that I want to pass to getChangedFields function) to Schema.ObjectField[] fieldList in the calling function ?


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;
}
Answered by Clare Matthews

There's several ways you can assign values to Schema.sobjectField[]. If you just want a hard-coded list:


sObjectField[] fieldList = new sObjectField[] {
  Account.Name, Account.Industry, Account.CustomField__c
};
Or you can get fancy with a CMDT:
sObjectField[] fieldList = new sObjectField[0];
for(FieldMap__mdt value: FieldMap__mdt.getAll().values()) {
  fieldList.add(value.Field__c);
}
Or you could use strings:
Map fieldsForObject = sObjectType.Account.fields.getMap().clone();
Set fields = new Set { 'name','industry','field__c' };
fieldsForObject.keySet().retainAll(fields);
sObjectField[] fieldList = fieldsForObject.values();
Or you can use a field set:
sObjectField[] fieldList = new sObjectField[0];
for(FieldSetMember member: sObjectType.Account.fieldsets.someFieldSet.getFields()) {
  fieldList.add(member.getSObjectField());
}

Or any combination of the above, and other ways aside from this are also possible. It's really a matter of preference.



Your Answer

Interviews

Parent Categories