+ Start a Discussion
Zach AckermanZach Ackerman 

VF Sorting

I have the following code and visualforce. I wanted to give users the ability to click on the column headers to allow them to sort the table. Is this possible? I've seen a few things online, but was unable to get it to work with pagination. 

Apex: 
 
public with sharing class Pagination_min {

    Public Integer noOfRecords{get; set;}
    Public Integer size{get;set;}
    public ApexPages.StandardSetController setCon {
        get{
            if(setCon == null){
                size = 500;
                string OwnersId =  userinfo.getUserId() ;
                string Rectypeid =   '01240000000Uexl';
                string Rectypeid2 = '01240000000cnJS';
                string queryString = 'Select Name, StageName,FED__c,Broker__c,Broker_Name__c,Core_Product__c,LeadSource,Number_Quoted__c,CreatedDate FROM Opportunity Where OwnerId = :OwnersId AND IsClosed = False AND (RecordTypeId = :Rectypeid OR RecordTypeId= :RecTypeId2) order by Probability,FED__c asc';
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(queryString));
                setCon.setPageSize(size);
                noOfRecords = setCon.getResultSize();
            }
            return setCon;
        }set;
    }
     
    Public List<Opportunity> getOpps(){
        List<Opportunity> oppList = new List<Opportunity>();
        for(Opportunity o : (List<Opportunity>)setCon.getRecords())
            oppList.add(o);
        return oppList;
    }
     
    public pageReference refresh() {
        setCon = null;
        getOpps();
        setCon.setPageNumber(1);
        return null; 
    }
    
    
    
   }

Visual Force 
 
<apex:page controller="Pagination_min">
 <apex:sectionHeader title="My Opportunity List"/>
    <apex:form >
           <apex:commandButton value="New Opportunity" onClick="window.open('https://cs15.salesforce.com/006/e?retURL=%2F006%2Fo&RecordType=01240000000Uexl&ent=Opportunity');"/>
           <apex:commandButton value="Detailed Report" onClick="window.open('https://cs15.salesforce.com/00Oe0000000fRSG');"/>
       <apex:pageBlock id="pb">
       
            <apex:pageBlockTable value="{!opps}" var="o">
                <apex:column headerValue="Opportunity Name">  
                      <apex:outputlink value="/{!o.id}" target="__blank">{!o.Name}</apex:outputlink>  
                </apex:column>                  
                <apex:column value="{!o.StageName}"/>
                <apex:column headerValue="Effective Date" value="{!o.FED__c}"/>
                <apex:column headerValue="Broker Name">
                <apex:outputlink value="/{!o.Broker__c}" target="__blank">{!o.Broker_Name__c}</apex:outputlink>  
                 </apex:column>    
                <apex:column value="{!o.Core_Product__c}"/>
                <apex:column value="{!o.LeadSource}"/>
                <apex:column value="{!o.Number_Quoted__c}"/>
                <apex:column value="{!o.CreatedDate}"/>
            </apex:pageBlockTable>
            <apex:panelGrid columns="7">
                <apex:commandButton status="fetchStatus" reRender="pb" value="|<" action="{!setCon.first}" disabled="{!!setCon.hasPrevious}" title="First Page"/>
                <apex:commandButton status="fetchStatus" reRender="pb" value="<" action="{!setCon.previous}" disabled="{!!setCon.hasPrevious}" title="Previous Page"/>
                <apex:commandButton status="fetchStatus" reRender="pb" value=">" action="{!setCon.next}" disabled="{!!setCon.hasNext}" title="Next Page"/>
                <apex:commandButton status="fetchStatus" reRender="pb" value=">|" action="{!setCon.last}" disabled="{!!setCon.hasNext}" title="Last Page"/>
                <apex:outputText >{!(setCon.pageNumber * size)+1-size}-{!IF((setCon.pageNumber * size)>noOfRecords, noOfRecords,(setCon.pageNumber * size))} of {!noOfRecords}</apex:outputText>
                <apex:commandButton status="fetchStatus" reRender="pb" value="Refresh" action="{!refresh}" title="Refresh Page"/>
                <apex:outputPanel style="color:#4AA02C;font-weight:bold">
                    <apex:actionStatus id="fetchStatus" startText="Fetching..." stopText=""/>
                </apex:outputPanel>
            </apex:panelGrid>
        </apex:pageBlock>
    </apex:form>
</apex:page>



 
Alain CabonAlain Cabon
Hi,

With pagination, you have to re-run the SOQL query with the appropriate ordering (the data of the other pages are unknown by the client by definition).
  • bobbuzzard.blogspot.com: Sorting Visualforce Tables with JavaScript This will only sort the rows displayed on the page. If this page displayed a subset of rows in a collection, the sorted values wouldn’t reflect the full dataset. In this scenario I’d re-run the SOQL query with the appropriate ordering or sort the collection of data server side.           
 http://bobbuzzard.blogspot.com/2014/09/sorting-visualforce-tables-with.html
  • Here is a very simple example of how you could implement sorting using some visualforce and apex. The trick here is an apex:facet tag
http://salesforce.stackexchange.com/questions/44562/how-to-do-arrow-sorting-on-columns
 
Zach AckermanZach Ackerman
Thanks this was helpful. I was able to test and build with the sorting feature. However, now I'm struggling to include the previous,next,refresh, first page, last page info in the bottom of the table. I can't seem to adapt the code from my original post  to the new code that allows for sorting. Is there a way to make the sorting and the page references work below?

Apex with Sorting:

public class myClass{
    
    
    
    public String sortField {get;set;}
    public String myOrder {get;set;}
    public myClass(){
        // Default setting for the sorting
        sortField = 'Probability';
        sortfield='FED__c';
        myOrder = 'ASC';
    }

    public List<Opportunity> getOpportunities(){
     
      string OwnersId =  userinfo.getUserId() ;
      string Rectypeid =   '01240000000Uexl';
      string Rectypeid2 = '01240000000cnJS';
        String q = 'Select Name,StageName,FED__c,Broker__c,Broker_Name__c,Core_Product__c,LeadSource,Number_Quoted__c,CreatedDate From Opportunity Where OwnerId = :OwnersId AND isClosed=False AND (RecordTypeId = :Rectypeid OR RecordTypeId= :RecTypeId2)';
        q += ' Order by ' +  String.escapeSingleQuotes(sortField) + ' ' + myOrder + ' LIMIT 500';
        return Database.query(q);
    }
}
Visual Force with Sorting: 
 
<apex:page controller="myClass">
<apex:sectionHeader title="My Opportunity List Sortable"/>
<apex:form >
<apex:commandButton value="New Opportunity" onClick="window.open('https://cs15.salesforce.com/006/e?retURL=%2F006%2Fo&RecordType=01240000000Uexl&ent=Opportunity');"/>
<apex:commandButton value="Detailed Report" onClick="window.open('https://cs15.salesforce.com/00Oe0000000fRSG');"/>
<apex:pageBlock >
<apex:pageBlockTable value="{!opportunities}" var="con" id="myTable">
    <apex:column >
        <apex:facet name="header">
            <apex:commandLink value="Name" reRender="myTable">
                <apex:param name="sortField" value="Name" assignTo="{!sortField}" />
                <apex:param name="myOrder" value="{!IF(myOrder == 'DESC', 'ASC','DESC')}" assignTo="{!myOrder}" />
            </apex:commandLink>
        </apex:facet>
        <apex:outputlink value="/{!con.id}" target="__blank">{!con.Name}</apex:outputlink> 
    </apex:column>
    <apex:column >
        <apex:facet name="header">
            <apex:commandLink value="StageName" reRender="myTable">
                <apex:param name="sortField" value="StageName" assignTo="{!sortField}" />
                <apex:param name="myOrder" value="{!IF(myOrder == 'DESC', 'ASC','DESC')}" assignTo="{!myOrder}" />
            </apex:commandLink>
        </apex:facet>
        <apex:outputField value="{!con.StageName}" />
    </apex:column>
    <apex:column >
     <apex:facet name="header">
            <apex:commandLink value="Effective Date" reRender="myTable">
                <apex:param name="sortField" value="FED__c" assignTo="{!sortField}" />
                <apex:param name="myOrder" value="{!IF(myOrder == 'DESC', 'ASC','DESC')}" assignTo="{!myOrder}" />
            </apex:commandLink>
        </apex:facet>
        <apex:outputField value="{!con.FED__c}" />
    </apex:column>
    <apex:column >
        <apex:facet name="header">
            <apex:commandLink value="Broker_Name__c" reRender="myTable">
                <apex:param name="sortField" value="Broker_Name__c" assignTo="{!sortField}" />
                <apex:param name="myOrder" value="{!IF(myOrder == 'DESC', 'ASC','DESC')}" assignTo="{!myOrder}" />
            </apex:commandLink>
        </apex:facet>
        <apex:outputlink value="/{!con.Broker__c}" target="__blank">{!con.Broker_Name__c}</apex:outputlink> 
    </apex:column>
 <apex:column >
     <apex:facet name="header">
            <apex:commandLink value="Core Product" reRender="myTable">
                <apex:param name="sortField" value="Core_Product__c" assignTo="{!sortField}" />
                <apex:param name="myOrder" value="{!IF(myOrder == 'DESC', 'ASC','DESC')}" assignTo="{!myOrder}" />
            </apex:commandLink>
        </apex:facet>
        <apex:outputField value="{!con.Core_Product__c}" />
    </apex:column>
    <apex:column >
     <apex:facet name="header">
            <apex:commandLink value="Lead Source" reRender="myTable">
                <apex:param name="sortField" value="LeadSource" assignTo="{!sortField}" />
                <apex:param name="myOrder" value="{!IF(myOrder == 'DESC', 'ASC','DESC')}" assignTo="{!myOrder}" />
            </apex:commandLink>
        </apex:facet>
        <apex:outputField value="{!con.LeadSource}" />
    </apex:column>
    <apex:column >
     <apex:facet name="header">
            <apex:commandLink value="Quoted Lives" reRender="myTable">
                <apex:param name="sortField" value="Number_Quoted__c" assignTo="{!sortField}" />
                <apex:param name="myOrder" value="{!IF(myOrder == 'DESC', 'ASC','DESC')}" assignTo="{!myOrder}" />
            </apex:commandLink>
        </apex:facet>
        <apex:outputField value="{!con.Number_Quoted__c}" />
    </apex:column>
    <apex:column >
     <apex:facet name="header">
            <apex:commandLink value="Create Date" reRender="myTable">
                <apex:param name="sortField" value="CreatedDate" assignTo="{!sortField}" />
                <apex:param name="myOrder" value="{!IF(myOrder == 'DESC', 'ASC','DESC')}" assignTo="{!myOrder}" />
            </apex:commandLink>
        </apex:facet>
        <apex:outputField value="{!con.CreatedDate}" />
    </apex:column>    
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>