Newer Version Available
Building a Custom List Controller
A custom list controller is similar to a standard list controller. Custom list controllers can implement Apex logic that you define to show or act on a set of records.
For example you can create the following custom list controller based on
a SOQL
query:
1public class opportunityList2Con {
2 // ApexPages.StandardSetController must be instantiated
3 // for standard list controllers
4 public ApexPages.StandardSetController setCon {
5 get {
6 if(setCon == null) {
7 setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
8 [SELECT Name, CloseDate FROM Opportunity]));
9 }
10 return setCon;
11 }
12 set;
13 }
14
15 // Initialize setCon and return a list of records
16 public List<Opportunity> getOpportunities() {
17 return (List<Opportunity>) setCon.getRecords();
18 }
19}The following Visualforce markup
shows how the custom controller above can be used in a
page:
1<apex:page controller="opportunityList2Con">
2 <apex:pageBlock>
3 <apex:pageBlockTable value="{!opportunities}" var="o">
4 <apex:column value="{!o.Name}"/>
5 <apex:column value="{!o.CloseDate}"/>
6 </apex:pageBlockTable>
7 </apex:pageBlock>
8</apex:page>You can also create a custom list controller that uses anti- and semi-joins as part of
the SOQL query. The following code is implemented as an extension to the account
standard
controller:
The
page that displays these records uses a mix of standard list controller actions, but
depends on iterating over the records returned from the custom list
controller:
1public with sharing class AccountPagination {
2 private final Account acct;
3
4 // The constructor passes in the standard controller defined
5 // in the markup below
6 public AccountPagination(ApexPages.StandardSetController controller) {
7 this.acct = (Account)controller.getRecord();
8 }
9
10 public ApexPages.StandardSetController accountRecords {
11 get {
12 if(accountRecords == null) {
13 accountRecords = new ApexPages.StandardSetController(
14 Database.getQueryLocator([SELECT Name FROM Account WHERE Id NOT IN
15 (SELECT AccountId FROM Opportunity WHERE IsClosed = true)]));
16 }
17 return accountRecords;
18 }
19 private set;
20 }
21 public List<Account> getAccountPagination() {
22 return (List<Account>) accountRecords.getRecords();
23 }
24}1<apex:page standardController="Account" recordSetVar="accounts" extensions="AccountPagination">
2 <apex:pageBlock title="Viewing Accounts">
3 <apex:form id="theForm">
4 <apex:pageBlockSection >
5 <apex:dataList value="{!accountPagination}" var="acct" type="1">
6 {!acct.name}
7 </apex:dataList>
8 </apex:pageBlockSection>
9 <apex:panelGrid columns="2">
10 <apex:commandLink action="{!previous}">Previous</apex:commandlink>
11 <apex:commandLink action="{!next}">Next</apex:commandlink>
12 </apex:panelGrid>
13 </apex:form>
14 </apex:pageBlock>
15</apex:page>