Ronnie
Ronnie

Reputation: 1073

Display results of unknown SOQL query

I have a requirement that I'd like to know if it is possible. I have visualforce page which will display the results of a SOQL query, however the SOQL query is dynamic and could be a query on Custom Objects or Standard Obejcts. I'm currently hard coding a SOQL query into the controller class whilst trying to figure out how it will work. I intend to display the results of the SOQL query in a pageBlockTable or dataTable in the Apex.

Is this possible in Salesforce, if so could anyone give me an example of how it would work both in Visualforce and Apex?

Upvotes: 2

Views: 917

Answers (1)

eyescream
eyescream

Reputation: 19637

You should read about "dynamic references" (also called "dynamic bindings"). A good starting point: http://www.salesforce.com/us/developer/docs/pages/Content/pages_dynamic_vf_sample_standard.htm

Basically if you have String fieldName = 'AccountNumber';, later in Visualforce you can refer to it directly:

<apex:outputField value="{!a.AccountNumber}"> or dynamically:

<apex:outputField value="{!a[fieldName]}">.

This is similar to having a.AccountNumber or a.get('AccountNumber') in Apex. Check out for example getting Value of a field by its Name in apex salesforce if you've never seen it.


You'll have to be careful around them because if your base object won't be account it will fail (for example there's no Contact.AccountNumber field). The example above deals with Accounts only but it'd be a good intro anyway.

Once you familiarize yourself with the basic idea you can explore world of fieldsets - predefined groups of fields that should come together - you can use them both for displaying and querying data, basically they're more powerful than hardcoded list of strings with the field names (like in first link) but still same idea.

At least you'll know now what keywords to look for ;)

Upvotes: 2

Related Questions