Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

This is my query...

List<Opportunity> opportunities = Database.query('SELECT OwnerId, Amount, Probability, ExpectedRevenue ' +  mycustomatt + ' FROM OPPORTUNITY ' + ' where isClosed = false');

mycustomatt is a String that is determine at runtime.

If I iterate over the opportunities, how can I get the value for mycustomatt?

for (Opportunity opportunity: opportunities) {
    // can get amount by doing
    System.debug('amount=' + opportunity.Amount);
    // ??? But how do I get the values for my customatt
    // ???

Thanks

share|improve this question
    
possible duplicate of update a records using generic fields –  eyescream Feb 11 '13 at 14:42
add comment

1 Answer 1

up vote 4 down vote accepted

Since the other question relates technically to updating and not retrieving I'll give an answer here as well, as well as a security nod. Though in general its pretty much the same principle and area of Apex you need to understand. That being Dynamic Apex and also the methods described on the SObject class, specifically in your case the 'get' methods. In short the following will give you what you want.

opportunity.get(mycustomatt);

If your custom attribute was of type String, you would cast it as follows...

String mycustomattValue = (String) opportunity.get(mycustomatt);

NOTE: You also need to keep in mind SOQL Injection considerations, as described here. Even if your code is providing the additional SOQL query information (as apposed to some end user prompt or config), its usually good practice to follow the recommendations here, just in case the situation changes in your code in the future.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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