Search code examples
salesforceapex-codeapex

Dynamically Access Fields in Salesforce APEX


I am writing an APEX trigger to validate data entry on an object. I have many fields that follow a similar naming format and are all the same datatype:

Field 1
Field 2
etc.
Field 10

I want to loop through the fields and add an error if any fails validation:

for (i=1; i<=10; i++){
    if !validate(Object.get('Field '+String.valueOf(i)){
        \\ Here I need code that can add an error to "Field i"
    }
}

The problem is that Object.get(fieldname) doens't return a reference to the field itself. It returns the value in that field. I found a thread here

https://developer.salesforce.com/forums/?id=906F000000091aFIAQ

that seems to try to address this question, but isn't resolved. Can anyone definitively say that this is or isn't possible in salesforce APEX?


Solution

  • Not possible. You can addError() to your whole sObject but not to fields referenced dynamically. The result will be that the error will appear on top of the page rather than on this particular field.

    Check https://salesforce.stackexchange.com/questions/79291/how-to-use-adderror-with-a-dynamically-derived-field-name and there's an idea to upvote: https://success.salesforce.com/ideaview?id=08730000000GoC5AAK