function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
rmranjith8881.3927046400771116E12rmranjith8881.3927046400771116E12 

sorting problem

Hi All,

I have a Sorting problem with my controller,

I am unable to sort the records when i click on column header,

can you people look into this and guide me how to achieve this?

Thanks in advance.............

here are my controller and Visualforce page,

Controller:

public with sharing class studentSponsorController{
public List<Opportunity> oppList{get; set;}//List of all Opportunities for data table
public Opportunity oppObj {get; set;}//object for oppotunity to get content on visualforce page
public String sortDirection = 'ASC';//variables to sort data table columns
public String sortExp = 'name';//variables to sort data table columns
public Contact con {set; get;}//variable for contact fo get content on visual force page
public Account acc {set; get;}//variable for Account fo get content on visual force page
public boolean isExport {get;set;}//variable to export data into excel
public Boolean isSearch {get;set;}//variable to verify searched values
//variables for search criteria
public String selectStr;
public String whereStr;
public String whereStr1;
public String whereStr2;
public String whereStr3;
public String whereStr4;
public String whereStr5;
//pagination for pageblock table
public ApexPages.StandardSetController pgn {
get {
if(pgn == null) {
pgn = new ApexPages.StandardSetController(oppList);
pgn.setPageSize(50);
}
return pgn;
}
set;
}
// indicates whether there are more records after the current page set..
public Boolean hasNext {
get {
return pgn.getHasNext();
}
set;
}
// indicates whether there are more records before the current page set..
public Boolean hasPrevious {
get {
return pgn.getHasPrevious();
}
set;
}
//Page number of the current displaying records
public Integer pageNumber
{
get
{
return pgn.getPageNumber();
}
set;
}
//Returns the previous page of records
public void previous()
{
pgn.previous();
}
//Returns the next page of records
public void next()
{
pgn.next();
}
// Initialize setPGN and return a list of records
public List<Opportunity> getOpportunityList() {
oppList = [Select Id, Name,AccountId, Account.Id, Account.Name, Record_Type_Name__c,
StageName,
Sponsorship_For__c, Std__c, Student_Name__c, Sponsorship_Date__c,
Student_Name__r.STD__c
FROM
Opportunity
WHERE
Recordtype.name = 'Education Sponsor' order by Std__c ASC LIMIT 1000];
return (List<Opportunity>) pgn.getRecords();
}
//logic to sort the data table values
public String sortExpression{
get{
return sortExp;
}
set{
//if the column is clicked on then switch between Ascending and Descending modes
if (value == sortExp)
sortDirection = (sortDirection == 'ASC')? 'DESC' : 'ASC';
else
sortDirection = 'ASC';
sortExp = value;
}
}
//Logic to sorting in asce/desce
public String getSortDirection(){
//if not column is selected
if (sortExpression == null || sortExpression == '')
return 'ASC';
else
return sortDirection;
}
//logic to view sorted data
public PageReference ViewData() {
//build the full sort expression
String sortFullExp = sortExpression + ' ' + sortDirection;
//query the database based on the sort expression
try{
String RecTypeName = 'Education Sponsor';
OpportunityRecordTypes__c edSponsorSort = OpportunityRecordTypes__c.getValues('RT1');//object to get record type using custom settings
if(RecTypeName == 'Education Sponsor'){
RecTypeName = edSponsorSort.RecordTypeName__c;
}
if(isSearch == false){
oppList = Database.query('Select Id, Name, Account.Id, Account.Name, Record_Type_Name__c, StageName, Sponsorship_For__c, Std__c, Student_Name__c, Sponsorship_Date__c,Student_Name__r.STD__c FROM Opportunity WHERE Recordtype.name = :RecTypeName ORDER BY ' + sortFullExp + ' limit 1000');
}else{
oppList = Database.query(selectStr+ whereStr+' ORDER BY ' + sortFullExp + ' limit 1000');
}
}catch(Exception e ) {
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING, e.getMessage() ));
}
return null;
}
//Controller
public studentSponsorController(){
try{
oppList = [Select Id, Name,AccountId, Account.Id, Account.Name, Record_Type_Name__c,
StageName,
Sponsorship_For__c, Std__c, Student_Name__c, Sponsorship_Date__c,
Student_Name__r.STD__c
FROM
Opportunity
WHERE
Recordtype.name = 'Education Sponsor' order by Std__c ASC LIMIT 1000];
pgn = new ApexPages.StandardSetController(oppList);
pgn.setPageSize(50);
oppObj = new Opportunity();
con = new Contact();
isSearch = false;
if(Apexpages.currentPage().getParameters().get('Export') != null){
isExport = true;
}
else{
isExport = false;
}
}catch(Exception e ) {
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING, e.getMessage() ));
}
}
//Logic to view respective opportunity record
public PageReference View() {
Opportunity oppTemp = new Opportunity(id=ApexPages.currentPage().getParameters().get('Id'));
PageReference stundentSponsorPage = new ApexPages.StandardController(oppTemp).view();
return stundentSponsorPage ;
}
//Getting list of all opprtunites
public List<Opportunity> getOppList() {
//return oppList;
return (List<Opportunity>) pgn.getRecords();
}
//logic to reset searched values
public void reset() {
oppObj = new Opportunity();
}
//method to get search results
public void dynamicSearch(){
try{
isSearch = true;
selectStr =' Select Id, Name,AccountId, Account.Id, Account.Name, Record_Type_Name__c,Student_Name__r.STD__c, StageName, Sponsorship_For__c, Std__c, Student_Name__c, Sponsorship_Date__c ' +
' FROM Opportunity WHERE Recordtype.name = \''+'Education Sponsor\'';
whereStr ='';
String orderBy=' order by Std__c ASC limit 1000';
whereStr1 = (con.STD__c != null) ? whereStr + ' Student_Name__r.STD__c = \''+ con.STD__c+'\'' : '';
whereStr2 = (oppObj.Student_Name__c!=null) ? whereStr + ' Student_Name__c = \''+ oppObj.Student_Name__c+'\'' : '';
whereStr3 = (oppObj.AccountId != null) ? whereStr + ' AccountId = \''+ oppObj.AccountId+'\'' : '';
whereStr4 = (oppObj.Sponsorship_For__c != null) ? whereStr + ' Sponsorship_For__c = \''+ oppObj.Sponsorship_For__c+'\'' : '';
whereStr5 = (oppObj.Name !='') ? whereStr + ' Name Like \'%'+oppObj.Name+'%\' ' : '';
whereStr =(whereStr1.length()>0) ? whereStr + ' AND ' + whereStr1 : whereStr;
whereStr =(whereStr2.length()>0) ? whereStr + ' AND ' + whereStr2 : whereStr;
whereStr =(whereStr3.length()>0) ? whereStr + ' AND ' + whereStr3 : whereStr;
whereStr =(whereStr4.length()>0) ? whereStr + ' AND ' + whereStr4 : whereStr;
whereStr =(whereStr5.length()>0) ? whereStr + ' AND ' + whereStr5 : whereStr;
oppList = Database.query(selectStr + whereStr + orderBy);
pgn = new ApexPages.StandardSetController(oppList);
pgn.setPageSize(25);
}catch(Exception e) {
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING, e.getMessage()));
}
}
//method to export data into excel
public PageReference export(){
isExport = true;
return null;
}
}

Visualforce page:

<apex:page controller="studentSponsorController" contentType="{!IF(isExport = true, 'application/vnd.ms-excel#StudentSponsorReport.xls', '')}" sidebar="false" standardStylesheets="true" rendered="{!$User.Allow_Student_Sponsor_Report__c == true}">
<apex:sectionHeader title="Student Sponsor's Report View" rendered="{!(isExport = false)}"/>
<form name="PrintInformationTop">
<Center>
<input type="button" value=" Print Report " onClick="window.print()"/>
</Center>
</form>
<apex:pageMessages ></apex:pageMessages>
<apex:form >
<apex:pageBlock title="Legends" rendered="{!(isExport = false)}">
<Center>
<apex:commandButton action="{!export}" value="Export Report" rendered="{!AND(isExport = false)}" reRender=""/>
</Center>
<apex:pageBlockSection >
<apex:panelGrid columns="4" title="LEGENDS" width="1200">
<apex:image alt="Yellow" url="https://cs6.salesforce.com/resource/1390282686000/Yellow">Sponsor Name(Account Name) - &nbsp;</apex:image>
<apex:image alt="Green" url="https://cs6.salesforce.com/resource/1390282619000/Green">Student Sponsored - &nbsp;</apex:image>
<apex:image alt="Orange" url="https://cs6.salesforce.com/resource/1390282660000/Orange">Sponsor Prospecting - &nbsp;</apex:image>
<apex:image alt="Red" url="https://cs6.salesforce.com/resource/1390282570000/Red">Student Not Sponsored - &nbsp;</apex:image>
</apex:panelGrid>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageblock title="Filtering Criteria" id="pb1" rendered="{!(isExport = false)}">
<apex:pageBlockSection columns="5">
<apex:inputField value="{!con.STD__c }" label="Student Standards"/>
<apex:inputField value="{!oppObj.Student_Name__c}" label="Student Name"/>
<apex:inputField value="{!oppObj.AccountId}" label="Sponsor Name"/>
<apex:inputField value="{!oppObj.Sponsorship_For__c}" label="Sponsorship For"/>
<apex:inputText value="{!oppObj.Name}" label="Opportunity Name"/>
</apex:pageBlockSection>
<apex:pageBlockButtons location="bottom">
<apex:commandButton value="Search" action="{!dynamicSearch}" rerender="pb2,pgNavigate" status="status1"/>
<apex:commandButton value="Reset" action="{!reset}" rerender="pb1" status="status1"/>
</apex:pageBlockButtons>
<apex:actionstatus id="status1">
<apex:facet name="start">
<img class="waitingImage" src="/img/loading.gif" title="Please Wait..." />
<span class="waitingDescription">Loading...</span>
</apex:facet>
</apex:actionstatus>
</apex:pageblock>
<apex:pageBlock title="Student Sponsor Report">
<apex:outputLabel style="font-weight:bold;font-size:12px;" rendered="{!(isExport = false)}">Sort Columns</apex:outputLabel>
<img src="/s.gif" alt="Help" class="helpIcon" title="{!$Label.Note}"/>
<apex:pageBlockTable value="{!OpportunityList}" var="o" rows="1000" id="pb2">
<apex:column >
<apex:facet name="header">
<apex:commandLink action="{!ViewData}" value="Student Standard{!IF(sortExpression=='Student_Name__r.STD__c',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdSort1" title="Click on this link to get values sorted in Ascending/Descending Order">
<apex:param value="Student_Name__r.STD__c" name="column" assignTo="{!sortExpression}" ></apex:param>
</apex:commandLink>
</apex:facet>
<apex:outputField value="{!o.Student_Name__r.STD__c }"/>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:commandLink action="{!ViewData}" value="Student Name{!IF(sortExpression=='Student_Name__c',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdSort2">
<apex:param value="Student_Name__c" name="column" assignTo="{!sortExpression}" ></apex:param>
</apex:commandLink>
</apex:facet>
<apex:outputField value="{!o.Student_Name__c}"/>
</apex:column>
<apex:column >
<div style="background-color:{!If(o.Account.Name != Null,'‪#‎FFFF00‬','‪#‎FFFFFF‬' )};">
{!o.Account.Name}
</div>
<apex:facet name="header">
<apex:commandLink action="{!ViewData}" value="Sponsor Name{!IF(sortExpression=='Account.Name',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdSort3">
<apex:param value="Account.Name" name="column" assignTo="{!sortExpression}" ></apex:param>
</apex:commandLink>
</apex:facet>
</apex:column>
<apex:column headerValue="Sponsorship For">
<a href="/{!o.Account.Id}" id="{!o.Account.Id}" onblur="LookupHoverDetail.getHover('{!o.Account.Id}').hide();" onfocus="LookupHoverDetail.getHover('{!o.Account.Id}', '/{!o.Account.Id}/m?retURL=%2F{!o.Account.Id}&isAjaxRequest=1').show();" onmouseout="LookupHoverDetail.getHover('{!o.Account.Id}').hide();" onmouseover="LookupHoverDetail.getHover('{!o.Account.Id}', '/{!o.Id}/m?retURL=%2F{!o.Account.Id}&isAjaxRequest=1').show();">
<div style="background-color:{!If(o.StageName = "Posted",'‪#‎00CC33‬',If(o.StageName = "Prospecting",'‪#‎FF9900‬','‪#‎FF0000‬'))};">
{!o.Sponsorship_For__c}
</div>
</a>
</apex:column>
<apex:column >
<div style="background-color:{!If(o.StageName = "Posted",'#00CC33',If(o.StageName = "Prospecting",'#FF9900','#FF0000'))};">
{!o.StageName}
</div>
<apex:facet name="header">
<apex:commandLink action="{!ViewData}" value="Stage Name{!IF(sortExpression=='StageName',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdSort5">
<apex:param value="StageName" name="column" assignTo="{!sortExpression}" ></apex:param>
</apex:commandLink>
</apex:facet>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:commandLink action="{!ViewData}" value="Sponsroship Date{!IF(sortExpression=='Sponsorship_Date__c',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdSort6">
<apex:param value="Sponsorship_Date__c" name="column" assignTo="{!sortExpression}" ></apex:param>
</apex:commandLink>
</apex:facet>
<apex:outputField value="{!o.Sponsorship_Date__c}"/>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:commandLink action="{!ViewData}" value="Opportunity Name{!IF(sortExpression=='Name',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdSort7">
<apex:param value="Name" name="column" assignTo="{!sortExpression}" ></apex:param>
</apex:commandLink>
</apex:facet>
<apex:commandLink action="{!View}" immediate="true" target="_blank">{!o.Name}
<apex:param name="id" value="{!o.id}"/>
</apex:commandLink>
</apex:column>
</apex:pageBlockTable>
<!--Pagination for PageBlock Table -->
<apex:outputPanel layout="block" styleClass="pSearchShowMore" id="pgNavigate">
<center>
<font style="color:red">Total Records Found: <apex:outputText rendered="{!IF(pgn.resultSize==10000,true,false)}">10000 +</apex:outputText><apex:outputText rendered="{!IF(pgn.resultSize < 10000,true,false)}">{!pgn.resultSize}</apex:outputText>
&nbsp;<apex:image url="/img/search_prevarrow_disabled.gif" styleClass="prevArrow" rendered="{!NOT(pgn.HasPrevious)}"/>
<apex:image url="/img/search_prevarrow.gif" title="Previous Page" styleClass="prevArrow" rendered="{!pgn.HasPrevious}"/>
<apex:commandLink action="{!Previous}" title="Previous Page" value="Previous Page" rendered="{!pgn.HasPrevious}"/>
<apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(pgn.HasPrevious)}">Previous Page</apex:outputPanel>
&nbsp;({!IF(pgn.PageNumber == 1,1,((pgn.PageNumber -1) * pgn.PageSize)+1)}-{!IF(pgn.resultSize < pgn.PageSize,pgn.resultSize,pgn.PageNumber * pgn.pageSize)})&nbsp;
<apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(pgn.HasNext)}">Next Page</apex:outputPanel>
<apex:commandLink title="Next Page" value="Next Page" rendered="{!pgn.HasNext}" action="{!Next}"/>&nbsp;
<apex:image url="/img/search_nextarrow.gif" title="Next Page" styleClass="nextArrow" rendered="{!pgn.HasNext}"/>
<apex:image url="/img/search_nextarrow_disabled.gif" rendered="{!NOT(pgn.HasNext)}"/></font>
</center>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>
ShashForceShashForce
Hi,

Please see if these links help:

http://help.salesforce.com/apex/HTViewSolution?id=000171025&language=en_US
http://www.sundoginteractive.com/sunblog/posts/a-recipe-for-column-sorting-salesforce-visualforce-page
http://funwithsfdc.blogspot.co.uk/2013/10/jquery-tablesorter-meets.html

If this answers your question, please mark this as the Best Answer for this post, so that others can benefit from this post.

Thanks,
Shashank
SANKAR NSANKAR N
Hi,

  By defalut list has sort() method, please try to use respective to your flow.

 Regards,
Sankar