Skip to content

Instantly share code, notes, and snippets.

@barelyknown
Created November 16, 2011 06:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save barelyknown/1369399 to your computer and use it in GitHub Desktop.
Save barelyknown/1369399 to your computer and use it in GitHub Desktop.
How do you check if a parent SObject has any children Sobjects in a VisualForce page without a wrapper class?
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>
@ionut-sultana
Copy link

Nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment