Skip to content

Instantly share code, notes, and snippets.

@capeterson
Created February 28, 2012 06:03
Show Gist options
  • Save capeterson/1930001 to your computer and use it in GitHub Desktop.
Save capeterson/1930001 to your computer and use it in GitHub Desktop.
Visualforce Query Component. Particularly useful for visualforce email templates.
global with sharing class Component_Query {
global String queryString {get; set;}
global List<sObject> results {get{
List<sObject> result = Database.Query(queryString);
return result;
} set; }
private static testmethod void contactTest(){
Contact c = new Contact(lastName = 'apex test contact');
insert c;
Test.startTest();
Component_Query component = new Component_Query();
component.queryString = 'SELECT id, name FROM Contact WHERE Id = \''+c.id+'\'';
List<sObject> result = component.results;
System.assertEquals(1,result.size(),'Expected a single contact record');
System.assertEquals('apex test contact',(String)result.get(0).get('name') );
}
}
<apex:component controller="Component_Query" access="global">
<apex:attribute name="QueryString" type="String" required="true" access="global" assignTo="{!queryString}"
description="A valid SOQL query in string form." />
<apex:variable value="{!results}" var="results"/>
<apex:componentBody />
</apex:component>
<messaging:emailTemplate subject="Contact Rejection" recipientType="Contact" relatedToType="Contact">
<messaging:htmlEmailBody >
<c:Query queryString="SELECT id, (SELECT Comments FROM ProcessSteps) FROM Contact WHERE Id = '{!relatedTo.id}'">
<apex:repeat value="{!results}" var="result">
<apex:repeat value="{!result['ProcessSteps']}" var="step">
{!step['Comments']}
</apex:repeat>
</apex:repeat>
</c:Query>
</messaging:htmlEmailBody>
</messaging:emailTemplate>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment