sObject in visualforce?
I have an apex controller which builds up a list to be displayed in a datatable. The list combines different object, so the variable I create is a List
Say all the objects in this list have an "external__c" field. How do I tell the visualforce to render this field? Using {!obj.external__c} will开发者_如何学Python not work since it is an sObject.
If you've got a list of SObjects you can get a common field using obj.get('external__c')
though you generally have to cast the result to a type to be able to use it.
You can create a custom class in code which you can fill with various objects:
// inside the controller do this:
public class COutputObject
{
private SObject sObj = null;
public string strField get {return (string)sObj.get('external__c'); }
public COutputObject(SObject s)
{
sObj = s;
}
}
// -- snip --
// then have a list of these which you'll loop over in the page
public list<COutputObject> liObjects = new list<COutputObject>();
// fill this with data
for(CustomObj__c sCustom : [select Id, external__c from CustomObj__c limit 200])
{
liObjects.add(new COutputObject(sCustom));
// etc.
for(CustomObj2__c sCustom : [select Id, external__c from CustomObj2__c limit 200])
{
liObjects.add(new COutputObject(sCustom));
// etc.
Not 100% sure if my syntax on the getter is correct, but it's close ;) Hopefully this will help you achieve what you're after!
Let's say the list property is declared like so in your controller: Public List<Beer__c> ColdOnes { get; set; }
. Well in Visualforce, you reference the beers by their property name in the controller... {!ColdOnes}
. The following is mostly taken from the Visualforce guide, but I have adapted it to suit our thist-quenching subject matter :)
<apex:dataTable value="{!ColdOnes}" var="co" id="theTable" rowClasses="odd,even" styleClass="tableClass">
<apex:facet name="caption">table caption</apex:facet>
<apex:facet name="header">table header</apex:facet>
<apex:facet name="footer">table footer</apex:facet>
<apex:column>
<apex:facet name="header">Beer Name</apex:facet>
<apex:facet name="footer">column footer</apex:facet>
<apex:outputText value="{!co.name}"/>
</apex:column>
<apex:column>
<apex:facet name="header">Alcohol Volume</apex:facet>
<apex:facet name="footer">column footer</apex:facet>
<apex:outputText value="{!co.alcohol_volume__c}"/>
</apex:column>
</apex:dataTable>
Just be aware that if you are setting ColdOnes with a queried value in your code, you need to select the fields you intend to output in your Visualforce. So:
ColdOnes=[select name, alcohol_volume__c from Beer__c where blahblahblah];
Well, I'm off for a pint. Hope that helps!
精彩评论