Friday, August 4, 2017

Sorting Tables In Visualforce

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 5 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 >
   <apex:pageblocktable value="{!accList}" var="rec" id="pgblcktbl">
     <apex:column value="{!rec.name}"/>
     <apex:column value="{!rec.annualrevenue}"/>
     <apex:column value="{!rec.accountnumber}"/>
   </apex:pageblocktable>
  </apex:pageBlock>
 </apex:form>

</apex:page>


Controller:

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 5];
 }
 Public void sortMethod(){
  if(selectedField == 'Name')
     accList = [select name,accountnumber,annualrevenue from account where id IN:accList order by Name limit 5 ];
  else if(selectedField == 'AccountNumber')
     accList = [select name,accountnumber,annualrevenue from account where id IN:accList order by AccountNumber limit 5 ];
  else if(selectedField == 'Annualrevenue')
    accList = [select name,accountnumber,annualrevenue from account where id IN:accList order by Annualrevenue desc limit 5 ];
 }

}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.