[SalesForce] Access fields dynamically in a trigger

I need to use dynamic fields in a for loop so that i can pick up the values from different field on insertion of an object accordingly.

Below mentioned are the fields which needs to be dynamically accessed.

enter image description here

Is there a way where we can use something like Target_Name_[i]__c in the loop so that on every iteration it picks up the respective field value?

Best Answer

The SObject class has dynamic get methods that allow you to specify a string. You could, for example, do something like:

for (MyObject__c record : trigger.new)
{
    for (Integer i = 1; i < 8; i++)
    {
        try
        {
            String target = (String)record.get('Target_Name_' + i + '__c');
            if (target == null) break;
            Object targetValue = record.get(target);
            // further processing...
        }
        catch (SObjectException e)
        {
            // target field not defined
            // validate using addError?
        }
    }
}
Related Topic