How to set a field value based on a long list of other fields

I’m looking for a best practice suggestion here as there are a couple of ways to solve this.

Based on if any of about 40 fields have any value I want to run a specific approval step.

So my first guess out of the gate was to create a new custom field and then use a formula to set the value. But since the 40 fields have a variety of types (picklist, text, checkbox) that was proving rather tedious (and I guess I would hit some sort of limit rather quick).

So my second guess was a trigger. So as I was coding I thought it would make sense to create a new object that contains the list of fields and then just reference that in my trigger. Cleans up the code a bit and makes maintenance a bit easier.

I’m a bit new to the platform, so I might have missed something obvious that others know about.

Any ideas that I might have missed?

Answer

SObject has map-like methods that work well for this type of logic. There are also compile-time checked SObjectType tokens that can be used as the keys (instead of name strings). So where you want to execute the same logic on many fields you can just iterate over the fields:

trigger MyTrigger on MyObject__c (...) {
    SObjectField[] fields = new SObjectField[] {
        MyObject__c.Field1__c,
        MyObject__c.Field2__c,
        ...
    };
    for (MyObject__c o : Trigger.new) {
        for (SObjectField f : fields) {
            if (o.get(f) != null) {
                ...
                break;
            }
        }
    }
}

On the specifics of what your particular problem, note that you’ll need to take care to code such a trigger to check for changing values and to check that there isn’t already an active approval process.

Attribution
Source : Link , Question Author : LeeFranke , Answer Author : Keith C

Leave a Comment