How can I build a complex Visualforce Dynamic Binding dynamically? Yeah, I realize the question seems a bit redundant, but I couldn't think of a better way to describe what I'm trying to do. The short version of my question is that I need to build a dynamic binding for both lookup (relationship) fields and standard fields in a Visualforce page, but I'm stuck on an error; how can I accomplish this?
Background
I have a few different sObjects to display, and I have a controlling Custom Setting object with records that indicates which fields should be displayed. The reason for this is to satisfy a requirement to display multiple fields from separate sObjects on a single Visualforce page with an administrative interface to update or add to those fields.
Here's some more detail. The sObjects are contained in a map using the sObject API Name as the key (Map<String, sObject> sObjectsByType
). Next, I have a list of Custom Setting records that contain the sObject API Name, the API Name of a Lookup Relationship (if applicable), and the API Name of the field (List<Field__c>
).
Issue
I ran into an issue with lookup fields and dynamic bindings while implementing this. Sometimes the f.Lookup_sObject__c
field is null
, and that causes a Visualforce error (Error evaluating dynamic reference ''
).
<apex:repeat value="{!Fields}" var="f">
<apex:inputfield value="{!sObjectsByType[f.sObject__c][f.Lookup_sObject__c][f.Field_API_Name__c]}" />
</apex:repeat>
What I've tried
I tried to dynamically render the inputfields, but even when I do that, I receive the same error because Visualforce cannot resolve the dynamic reference.
<apex:repeat value="{!Fields}" var="f">
<apex:inputfield value="{!sObjectsByType[f.sObject__c][f.Lookup_sObject__c][f.Field_API_Name__c]}" rendered="{!f.Lookup_sObject__c != null}" />
<apex:inputfield value="{!sObjectsByType[f.sObject__c][f.Field_API_Name__c]}" rendered="{!f.Lookup_sObject__c == null}" />
</apex:repeat>
Question
How can I use dynamic bindings on an <apex:inputField>
to display fields that are lookups to fields on other objects as well as fields that are not? Is this even possible?
f.Lookup_sObject__c
is null would it make sense to just hide that inputfield using something likerendered="{! f.Lookup_sObject__c != null}"
?