function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
katrinaxxkatrinaxx 

How to loop through ALL fields in Account object and invoke method on field

Map<String, Schema.SObjectType> gdMap = Schema.getGlobalDescribe();
Schema.Describesobjectresult dsr = gdMap.get('Account').getDescribe();
Map<String, Schema.SObjectField> fieldMap = dsr.fields.getMap();

 

if(testAccountObj.Name.containsAny(strCompare) {
}

 

Is there any way to code this such that the Name field is not hard coded? The requirement is to check ALL fields in the Account object and I don't want to have separate IF clauses for each field. Want it to be as dynamic as possible.  Is this even possible? 

 

Thanks!

sfdcfoxsfdcfox

Of course it's possible. But, you do know in this particular case, you might want to just use SOSL to have the index system search for values for you...

 

You could try to do it dynamically, but it would require significant amounts of code, something like:

 

SobjectField[] fields = Account.getDescribe().fields.getMap().values();
for(SObjectField field:fields) {
    if(testAccountObj.get(field)!=null && testAccountObj.get(field) instanceof String && ((String)testAccountObj.get(field)).containsAny(strCompare)) {
        System.debug('Match found in field: '+String.valueOf(field));
    }
}

More complex logic if you want to test non-strings as strings, but this should probably get you started.