Skip to content

Instantly share code, notes, and snippets.

@zokito
Forked from barelyknown/gist:1369399
Created October 25, 2013 13:56
Show Gist options
  • Save zokito/7155095 to your computer and use it in GitHub Desktop.
Save zokito/7155095 to your computer and use it in GitHub Desktop.
When looping through a set of Salesforce.com SObjects from a VisualForce page, you may want to test whether the SObject has any children without wrapping the SObjects in a wrapper class. Here's how:
Controller:
Create a property in the controller that is a map of the parent IDs and Boolean flag.
public Map<Id, Boolean> hasChildren {
get {
if (this.hasChildren == null) {
for (Parent__c parent : [select id, (select id from children__r) from parent__c]) {
if (parent.children__r.size() > 0) {
this.hasChildren.put(parent.id,true);
} else {
this.hasChildren.put(parent.id,false);
}
}
}
return this.hasChildren;
}
set {
this.hasChildren = value;
}
}
Visualforce Page:
Use dynamic bindings to check if the parent has any children while looping in Visualforce. This example renders the text if there are children.
<apex:repeat value="{!parents}" var="parent">
<apex:outputtext value="-----" rendered="{!hasChildren[parent.id]}" />
</apex:repeat>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment