Tuesday, September 2, 2014

Sorting tables in visualforce Pages.

Sorting tables in visualforce Pages.

A List of records returned by select query can be sorted using order by clause. The field with which the resulting list be sorted should be specified after the order by clause.
We can specify whether we want a ascending sorting or a descending sorting. If the ascending or descending is not specified then the query sorts in ascending order of the specified field.
For ascending just use the keyword "'ASC" and for descending use the keyword "DESC"
example:
1. List<Contact> conList = [select id,name,email from contact order by name desc];
2. List<account> accList = [Select id,name,accountnumber from account order by name asc] is same as below 
3.List<account> accList = [Select id,name,accountnumber from account order by name]

Here's an example that sorts a table showing 100 account records. Button sorts the table depending on the field selected for sorting

Visualforce Page:

<apex:page controller="sortDemoController">
 <apex:form >
  <apex:pageBlock >
   <apex:panelgrid columns="2">
    <apex:selectList value="{!selectedField }" size="1">
     <apex:selectOption itemValue="Name" itemLabel="Account Name"/>
     <apex:selectOption itemValue="AccountNumber" itemLabel="Account Number"/>
     <apex:selectOption itemValue="Annualrevenue" itemLabel="Annual Revenue"/>
    </apex:selectList>
    <apex:commandButton value="Sort Table" action="{!sortMethod}" reRender="pgblcktbl"/>
   </apex:panelgrid>
  </apex:pageBlock>
  <apex:pageBlock id="pgblcktbl">
   <apex:pageblocktable value="{!accList}" var="rec" >
     <apex:column value="{!rec.name}"/>
     <apex:column value="{!rec.annualrevenue}"/>
     <apex:column value="{!rec.accountnumber}"/>
   </apex:pageblocktable>
  </apex:pageBlock>
 </apex:form>
</apex:page>

Controller Class:

Public with sharing class sortDemoController {
Public List<account> accList{get;set;}
Public string selectedField {get;set;}
 Public sortDemoController(){
  accList = [select name,accountnumber,annualrevenue from account limit 100];
 }
 Public void sortMethod(){
  if(selectedField == 'Name')
     accList = [select name,accountnumber,annualrevenue from account where id IN:accList order by Name limit 100 ];
  else if(selectedField == 'AccountNumber')
     accList = [select name,accountnumber,annualrevenue from account where id IN:accList order by AccountNumber limit 100 ];
  else if(selectedField == 'Annualrevenue')
    accList = [select name,accountnumber,annualrevenue from account where id IN:accList order by Annualrevenue desc limit 100 ];
 }
}

 Out put:

save image










0 comments:

Post a Comment

 
| ,