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?


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++)
            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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.